// 全局变量
let canvas, ctx;
let isDrawing = false;
let isEraser = false;
let currentColor = '#000000';
let currentSize = 5;
let currentBrushType = 'normal'; // 当前画笔类型
let eraserSize = 20; // 橡皮擦大小
let currentShape = null; // 当前选择的形状
let shapeSize = 50; // 形状大小
let isDrawingShape = false; // 是否正在绘制形状
let shapeStartX = 0, shapeStartY = 0; // 形状起始点
let isShiftPressed = false; // 是否按住Shift键
let isHandTracking = false;
let isHandDrawing = false;
let lastX = 0, lastY = 0;

// 颜色主题数据
const colorThemes = {
    morandi: {
        name: '莫兰迪',
        colors: [
            '#E8D5C4', '#A8B5BE', '#B8A9C9', '#C4B5A0', 
            '#D4C4A8', '#A8C4B8', '#C4A8B8', '#B8C4A8'
        ]
    },
    mondrian: {
        name: '蒙德里安',
        colors: [
            '#FF0000', '#0000FF', '#FFFF00', '#000000',
            '#FFFFFF', '#FF6600', '#00FF00', '#FF00FF'
        ]
    },
    macaron: {
        name: '马卡龙',
        colors: [
            '#FFB3BA', '#BAFFC9', '#BAE1FF', '#FFFFBA',
            '#FFB3F7', '#B3FFE6', '#F7B3FF', '#E6FFB3'
        ]
    },
    memphis: {
        name: '孟菲斯',
        colors: [
            '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4',
            '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F'
        ]
    },
    rococo: {
        name: '洛可可',
        colors: [
            '#F4E4BC', '#E8B4B8', '#B4D2E7', '#C8E6C9',
            '#D1C4E9', '#FFCCBC', '#B2DFDB', '#FFECB3'
        ]
    }
};
// 移除绘画模式开关，现在使用系统画板式绘画

// 画布状态管理（用于撤回功能）
let canvasHistory = [];
let currentHistoryIndex = -1;
const maxHistorySize = 50; // 最大历史记录数量

// 语音识别相关
let recognition;
let isListening = false;

// 图片导入相关
let importedImages = []; // 存储导入的图片信息
let selectedImageIndex = -1; // 当前选中的图片索引

// 应用设置
let appSettings = {
    defaultBrushSize: 5,
    defaultColor: '#000000',
    voiceEnabled: true,
    voiceVolume: 0.8,
    speechRecognitionEnabled: true,
    recognitionLanguage: 'zh-CN',
    voiceSensitivity: 0.7,
    autoStopTime: 15
};

// 咒语数据
const spells = [
    {
        name: "Lumos",
        pronunciation: "LOO-mos",
        description: "点亮魔杖尖端，产生光源",
        effect: "light",
        forbidden: false
    },
    {
        name: "Nox",
        pronunciation: "NOKS",
        description: "熄灭Lumos咒语产生的光",
        effect: "dark",
        forbidden: false
    },
    {
        name: "Wingardium Leviosa",
        pronunciation: "wing-GAR-dee-um lev-ee-O-sa",
        description: "让物体漂浮在空中",
        effect: "float",
        forbidden: false
    },
    {
        name: "Alohomora",
        pronunciation: "al-oh-ho-MOR-ah",
        description: "解锁门或箱子",
        effect: "unlock",
        forbidden: false
    },
    {
        name: "Expecto Patronum",
        pronunciation: "ex-PEK-toh pa-TRO-num",
        description: "召唤守护神，驱赶摄魂怪",
        effect: "patronus",
        forbidden: false
    },
    {
        name: "Expelliarmus",
        pronunciation: "ex-pel-ee-AR-mus",
        description: "缴械咒，使对手的魔杖脱手",
        effect: "disarm",
        forbidden: false
    },
    {
        name: "Stupefy",
        pronunciation: "STEW-puh-fy",
        description: "昏迷咒，使目标失去知觉",
        effect: "stun",
        forbidden: false
    },
    {
        name: "Protego",
        pronunciation: "pro-TAY-go",
        description: "防护咒，反弹咒语",
        effect: "shield",
        forbidden: false
    },
    {
        name: "Accio",
        pronunciation: "AK-see-oh",
        description: "召唤咒，将物体召唤到施法者手中",
        effect: "summon",
        forbidden: false
    },
    {
        name: "Reparo",
        pronunciation: "re-PAR-oh",
        description: "修复咒，修复损坏的物体",
        effect: "repair",
        forbidden: false
    },
    {
        name: "Incendio",
        pronunciation: "in-SEN-dee-oh",
        description: "火焰咒，产生火焰",
        effect: "fire",
        forbidden: false
    },
    {
        name: "Aguamenti",
        pronunciation: "ah-gwah-MEN-tee",
        description: "清水如泉，产生水流",
        effect: "water",
        forbidden: false
    },
    {
        name: "Petrificus Totalus",
        pronunciation: "pe-TRI-fi-cus to-TAL-us",
        description: "全身束缚咒，使目标全身僵硬",
        effect: "freeze",
        forbidden: false
    },
    {
        name: "Sectumsempra",
        pronunciation: "sec-tum-SEM-pra",
        description: "神锋无影，造成严重切割伤害",
        effect: "cut",
        forbidden: false
    },
    {
        name: "Crucio",
        pronunciation: "KROO-see-oh",
        description: "钻心剜骨，造成极度痛苦",
        effect: "torture",
        forbidden: true
    },
    {
        name: "Imperio",
        pronunciation: "im-PEER-ee-oh",
        description: "夺魂咒，控制目标的思想和行为",
        effect: "control",
        forbidden: true
    },
    {
        name: "Avada Kedavra",
        pronunciation: "ah-VAH-dah ke-DAV-rah",
        description: "阿瓦达索命咒，立即致死",
        effect: "kill",
        forbidden: true
    },
    {
        name: "Obliviate",
        pronunciation: "oh-BLI-vee-ate",
        description: "遗忘咒，抹去记忆",
        effect: "forget",
        forbidden: false
    },
    {
        name: "Riddikulus",
        pronunciation: "ri-DIK-uh-lus",
        description: "滑稽滑稽，将博格特变成可笑的样子",
        effect: "ridiculous",
        forbidden: false
    },
    {
        name: "Silencio",
        pronunciation: "si-LEN-see-oh",
        description: "无声无息，使目标失声",
        effect: "silence",
        forbidden: false
    }
];

// 图纸数据 - 使用本地图纸文件夹中的图片
const templates = {
    "霍格沃茨建筑": [
        { name: "霍格沃茨城堡", image: "图纸/霍格沃茨建筑/霍格沃茨城堡.jpeg" },
        { name: "大礼堂", image: "图纸/霍格沃茨建筑/大礼堂.png" },
        { name: "图书馆", image: "图纸/霍格沃茨建筑/图书馆.png" },
        { name: "魁地奇球场", image: "图纸/霍格沃茨建筑/魁地奇球场.jpg" }
    ],
    "魔法生物": [
        { name: "凤凰福克斯", image: "图纸/魔法生物/凤凰福克斯.jpeg" },
        { name: "牙牙", image: "图纸/魔法生物/海格的小屋.jpg" },
        { name: "夜骐", image: "图纸/魔法生物/夜骐.jpg" },
        { name: "家养小精灵", image: "图纸/魔法生物/家养小精灵.webp" }
    ],
    "魔法物品": [
        { name: "魔杖", image: "图纸/魔法物品/魔杖.jpg" },
        { name: "分院帽", image: "图纸/魔法物品/分院帽.jpg" },
        { name: "活点地图", image: "图纸/魔法物品/活点地图.jpg" },
        { name: "时间转换器", image: "图纸/魔法物品/时间转换器.jpg" }
    ],
    "学院标志": [
        { name: "格兰芬多", image: "图纸/学院标志/格兰芬多.jpeg" },
        { name: "斯莱特林", image: "图纸/学院标志/斯莱特林.jpeg" },
        { name: "拉文克劳", image: "图纸/学院标志/拉文克劳.jpeg" },
        { name: "赫奇帕奇", image: "图纸/学院标志/赫奇帕奇.jpg" }
    ],
    "魔法植物": [
        { name: "曼德拉草", image: "图纸/魔法植物/曼德拉草.jpg" },
        { name: "魔鬼网", image: "图纸/魔法植物/魔鬼网.webp" },
        { name: "打人柳", image: "图纸/魔法植物/打人柳.png" },
        { name: "温室", image: "图纸/魔法植物/温室.jpg" }
    ],
    "魔法交通工具": [
        { name: "飞天扫帚", image: "图纸/魔法交通工具/飞天扫帚.jpg" },
        { name: "骑士公共汽车", image: "图纸/魔法交通工具/骑士公共汽车.jpg" },
        { name: "霍格沃茨特快", image: "图纸/魔法交通工具/霍格沃茨特快.jpg" },
        { name: "门钥匙", image: "图纸/魔法交通工具/门钥匙.png" }
    ]
};

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    // 添加图片导入按钮的事件监听器
    document.getElementById('importImageBtn').addEventListener('click', importImage);
    // 初始化烟花特效
    initializeFireworks();
    // 初始化分院测试
    initializeSortingTest();
    // 初始化魔杖测试
    initializeWandTest();
    // 初始化背景轮播
    initializeBackgroundSlideshow();
    // 初始化倒计时
    initializeCountdown();
    // 初始化电影回顾功能
    initMovieReview();
});

function initializeApp() {
    // 获取DOM元素
    canvas = document.getElementById('drawingCanvas');
    ctx = canvas.getContext('2d');
    // 手部追踪相关元素已移除
    
    // 加载设置
    loadSettings();
    
    // 设置画布
    setupCanvas();
    
    // 绑定事件
    bindEvents();
    
    // 生成咒语和图纸界面
    generateSpellsInterface();
    generateTemplatesInterface();
    
    // 初始化语音识别
    initializeSpeechRecognition();
    
    // 绑定魔法装饰事件
    bindMagicalWheel();
    
    // 初始化撤回按钮状态
    updateUndoButton();
    
    // 初始化绘画模式指示器
    updatePaintingModeIndicator();
    
    // 初始化颜色主题
    initializeColorTheme();
    
    // 初始化颜色圆盘
    initializeColorWheel();
    
    // 初始化音频功能
    initializeAudio();
    
    // 初始化图片计数器
    updateImageCounter();
    
    // 显示欢迎弹窗
    showWelcomeModal();
}

function loadSettings() {
    const savedSettings = localStorage.getItem('hogwartsSettings');
    if (savedSettings) {
        try {
            const parsedSettings = JSON.parse(savedSettings);
            appSettings = { ...appSettings, ...parsedSettings };
        } catch (e) {
            console.error('加载设置失败:', e);
        }
    }
}

function setupCanvas() {
    // 设置画布背景
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 设置绘图样式
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    
    // 初始化画笔颜色和大小
    ctx.strokeStyle = currentColor;
    ctx.lineWidth = currentSize;
    
    // 保存初始状态
    saveCanvasState();
}

// 保存画布状态
function saveCanvasState() {
    try {
        // 创建临时画布来合并绘图内容和导入的图片
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = canvas.width;
        tempCanvas.height = canvas.height;
        const tempCtx = tempCanvas.getContext('2d');
        
        // 绘制当前画布内容
        tempCtx.drawImage(canvas, 0, 0);
        
        // 绘制所有导入的图片
        importedImages.forEach((img, index) => {
            tempCtx.drawImage(img.element, img.x, img.y, img.width, img.height);
            
            // 如果是图纸类型，添加边框
            if (img.type === 'template') {
                tempCtx.strokeStyle = '#d4af37';
                tempCtx.lineWidth = 3;
                tempCtx.strokeRect(img.x, img.y, img.width, img.height);
            }
            
            // 为选中的图片添加高亮边框
            if (index === selectedImageIndex) {
                tempCtx.strokeStyle = '#ff0000';
                tempCtx.lineWidth = 2;
                tempCtx.setLineDash([5, 5]);
                tempCtx.strokeRect(img.x - 2, img.y - 2, img.width + 4, img.height + 4);
                tempCtx.setLineDash([]);
            }
        });
        
        // 保存合并后的画布状态
        const imageData = tempCanvas.toDataURL();
        
        // 如果当前不在历史记录末尾，删除后面的记录
        if (currentHistoryIndex < canvasHistory.length - 1) {
            canvasHistory = canvasHistory.slice(0, currentHistoryIndex + 1);
        }
        
        canvasHistory.push(imageData);
        
        // 限制历史记录数量
        if (canvasHistory.length > maxHistorySize) {
            canvasHistory.shift();
        } else {
            currentHistoryIndex++;
        }
        
        // 更新撤回按钮状态
        updateUndoButton();
        
        console.log('保存画布状态成功，当前历史记录数量:', canvasHistory.length, '当前索引:', currentHistoryIndex);
    } catch (error) {
        console.error('保存画布状态失败:', error);
    }
}

// 恢复画布状态
function restoreCanvasState() {
    try {
        console.log('尝试撤回，当前索引:', currentHistoryIndex, '历史记录数量:', canvasHistory.length);
        
        if (currentHistoryIndex > 0 && canvasHistory.length > 0) {
            // 获取上一个状态
            const previousState = canvasHistory[currentHistoryIndex - 1];
            
            if (previousState) {
                // 显示撤回中提示
                showNotification('正在撤回...', 'info');
                
                const img = new Image();
                img.onload = function() {
                    // 恢复画布状态
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0);
                    
                    // 更新索引
                    currentHistoryIndex--;
                    
                    // 更新撤回按钮状态
                    updateUndoButton();
                    
                    console.log('撤回成功，新索引:', currentHistoryIndex);
                    showNotification('已撤回上一步操作', 'success');
                };
                
                img.onerror = function() {
                    console.error('加载历史状态图片失败');
                    showNotification('撤回失败，请重试', 'error');
                };
                
                img.src = previousState;
            } else {
                console.log('历史状态为空');
                showNotification('撤回失败，历史状态为空', 'error');
            }
        } else {
            console.log('无法撤回，已经是第一步或没有历史记录');
            showNotification('无法撤回，已经是第一步', 'warning');
        }
    } catch (error) {
        console.error('撤回操作失败:', error);
        showNotification('撤回操作失败，请重试', 'error');
    }
}

// 更新撤回按钮状态
function updateUndoButton() {
    const undoBtn = document.getElementById('undoBtn');
    if (undoBtn) {
        console.log('更新撤回按钮状态，当前索引:', currentHistoryIndex, '历史记录数量:', canvasHistory.length);
        if (currentHistoryIndex > 0) {
            undoBtn.disabled = false;
            undoBtn.style.opacity = '1';
            undoBtn.title = `撤回上一步 (Ctrl+Z) - 可撤回 ${currentHistoryIndex} 次`;
            console.log('撤回按钮已启用');
        } else {
            undoBtn.disabled = true;
            undoBtn.style.opacity = '0.5';
            undoBtn.title = '无法撤回';
            console.log('撤回按钮已禁用');
        }
    } else {
        console.error('未找到撤回按钮元素');
    }
}

function bindEvents() {
    // 欢迎弹窗
    document.getElementById('enterButton').addEventListener('click', enterApp);
    
    // 工具栏事件
    document.getElementById('colorPicker').addEventListener('change', updateColor);
    document.getElementById('brushSize').addEventListener('input', updateBrushSize);
    document.getElementById('eraserSize').addEventListener('input', updateEraserSize);
    document.getElementById('undoBtn').addEventListener('click', function() {
        console.log('撤回按钮被点击');
        restoreCanvasState();
    });
    document.getElementById('saveBtn').addEventListener('click', saveImage);
    
    // 画笔下拉菜单事件
    document.getElementById('brushDropdownBtn').addEventListener('click', toggleBrushDropdown);
    document.querySelectorAll('.brush-option').forEach(option => {
        option.addEventListener('click', selectBrushType);
    });
    
    // 颜色下拉菜单事件
    document.getElementById('colorDropdownBtn').addEventListener('click', toggleColorDropdown);
    document.querySelectorAll('.color-theme-option').forEach(option => {
        option.addEventListener('click', selectColorTheme);
    });
    
    // 自定义颜色按钮事件
    document.getElementById('customColorBtn').addEventListener('click', toggleColorWheel);
    
    // RGB输入事件
    document.getElementById('applyRgbBtn').addEventListener('click', applyRgbColor);
    document.getElementById('rgbR').addEventListener('input', updateRgbPreview);
    document.getElementById('rgbG').addEventListener('input', updateRgbPreview);
    document.getElementById('rgbB').addEventListener('input', updateRgbPreview);
    
    // 橡皮下拉菜单事件
    document.getElementById('eraserDropdownBtn').addEventListener('click', toggleEraserDropdown);
    document.querySelectorAll('.eraser-option').forEach(option => {
        option.addEventListener('click', selectEraserAction);
    });
    
    // 形状下拉菜单事件
    document.getElementById('shapeDropdownBtn').addEventListener('click', toggleShapeDropdown);
    document.querySelectorAll('.shape-option').forEach(option => {
        option.addEventListener('click', selectShape);
    });
    
    // 形状大小控制
    document.getElementById('shapeSize').addEventListener('input', updateShapeSize);
    
    // 点击其他地方关闭下拉菜单
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.brush-dropdown')) {
            document.getElementById('brushDropdownContent').classList.remove('show');
            document.getElementById('brushSizeControl').classList.remove('show');
        }
        if (!e.target.closest('.eraser-dropdown')) {
            document.getElementById('eraserDropdownContent').classList.remove('show');
            document.getElementById('eraserSizeControl').classList.remove('show');
        }
        if (!e.target.closest('.shape-dropdown')) {
            document.getElementById('shapeDropdownContent').classList.remove('show');
            document.getElementById('shapeSizeControl').classList.remove('show');
        }
        if (!e.target.closest('.color-dropdown')) {
            document.getElementById('colorDropdownContent').classList.remove('show');
        }
        if (!e.target.closest('.custom-color-btn') && !e.target.closest('.color-wheel-container')) {
            document.getElementById('colorWheelContainer').classList.remove('show');
        }
        if (!e.target.closest('.audio-btn') && !e.target.closest('.audio-control-panel')) {
            document.getElementById('audioControlPanel').classList.remove('show');
        }
    });
    
    // 添加按钮提示
    document.getElementById('brushDropdownBtn').title = '选择画笔类型';
    document.getElementById('colorDropdownBtn').title = '选择颜色主题';
    document.getElementById('eraserDropdownBtn').title = '橡皮擦和清空功能';
    document.getElementById('shapeDropdownBtn').title = '绘制几何形状';
    document.getElementById('undoBtn').title = '撤回上一步 (Ctrl+Z)';
    document.getElementById('saveBtn').title = '保存图片';
    document.getElementById('spellsBtn').title = '咒语手册';
    document.getElementById('templatesBtn').title = '图纸库';
    
    // 快速颜色选择
    document.querySelectorAll('.color-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            currentColor = this.dataset.color;
            document.getElementById('colorPicker').value = currentColor;
            // 立即更新画笔颜色
            if (!isEraser) {
                ctx.strokeStyle = currentColor;
            }
        });
    });
    
    // 已移除手部追踪控制按钮
    
    // 弹窗按钮
    document.getElementById('voiceBtn').addEventListener('click', toggleVoiceRecognition);
    document.getElementById('spellsBtn').addEventListener('click', showSpellsModal);
    document.getElementById('templatesBtn').addEventListener('click', showTemplatesModal);
    
    // 帮助按钮
    document.getElementById('helpBtn').addEventListener('click', showHelpModal);
    
    // 音频按钮
    document.getElementById('audioBtn').addEventListener('click', toggleAudioPanel);
    
    // 设置按钮
    document.getElementById('settingsBtn').addEventListener('click', showSettings);
    
    // 设置面板事件
    bindSettingsEvents();
    
    // 初始化语音识别
    initializeSpeechRecognition();
    
    // 绑定魔法装饰事件
    bindMagicalWheel();
    
    // 鼠标绘图事件
    canvas.addEventListener('mousedown', handleCanvasMouseDown);
    canvas.addEventListener('mousemove', handleCanvasMouseMove);
    canvas.addEventListener('mouseup', handleCanvasMouseUp);
    canvas.addEventListener('mouseout', handleCanvasMouseUp);
    
    // 图片点击事件
    canvas.addEventListener('click', handleImageClick);
    
    // 触摸绘图事件
    canvas.addEventListener('touchstart', handleTouch);
    canvas.addEventListener('touchmove', handleTouch);
    canvas.addEventListener('touchend', stopDrawing);
    
    // 图片缩放事件
    canvas.addEventListener('wheel', handleImageWheel);
    
    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        // 跟踪Shift键状态
        if (e.key === 'Shift') {
            isShiftPressed = true;
        }
        
        if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
            e.preventDefault();
            restoreCanvasState();
        }
        
        // Delete键删除选中的图片
        if (e.key === 'Delete' && selectedImageIndex >= 0 && selectedImageIndex < importedImages.length) {
            e.preventDefault();
            deleteSelectedImage();
        }
        
        // Ctrl+Delete删除所有图片
        if ((e.ctrlKey || e.metaKey) && e.key === 'Delete') {
            e.preventDefault();
            deleteAllImages();
        }
        
        // 方向键控制图片移动
        if (importedImages.length > 0 && selectedImageIndex >= 0 && selectedImageIndex < importedImages.length) {
            const selectedImage = importedImages[selectedImageIndex];
            const moveStep = e.shiftKey ? 20 : 10; // Shift+方向键移动更快
            
            switch(e.key) {
                case 'ArrowUp':
                    e.preventDefault();
                    selectedImage.y = Math.max(0, selectedImage.y - moveStep);
                    redrawCanvas();
                    break;
                case 'ArrowDown':
                    e.preventDefault();
                    selectedImage.y = Math.min(canvas.height - selectedImage.height, selectedImage.y + moveStep);
                    redrawCanvas();
                    break;
                case 'ArrowLeft':
                    e.preventDefault();
                    selectedImage.x = Math.max(0, selectedImage.x - moveStep);
                    redrawCanvas();
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    selectedImage.x = Math.min(canvas.width - selectedImage.width, selectedImage.x + moveStep);
                    redrawCanvas();
                    break;
            }
        }
    });
    
    // 键盘释放事件
    document.addEventListener('keyup', function(e) {
        // 跟踪Shift键状态
        if (e.key === 'Shift') {
            isShiftPressed = false;
        }
    });

    // 图片导入功能
    document.getElementById('importImageBtn').addEventListener('click', importImage);
    
    // 音乐控制
    const musicToggleBtn = document.getElementById('musicToggleBtn');
    const volumeSlider = document.getElementById('volumeSlider');
    const backgroundMusic = document.getElementById('backgroundMusic');
    
    if (musicToggleBtn && backgroundMusic) {
        musicToggleBtn.addEventListener('click', function() {
            if (backgroundMusic.paused) {
                backgroundMusic.play();
                musicToggleBtn.textContent = '🎵 暂停音乐';
            } else {
                backgroundMusic.pause();
                musicToggleBtn.textContent = '🎵 播放音乐';
            }
        });
    }
    
    if (volumeSlider && backgroundMusic) {
        // 设置初始音量
        backgroundMusic.volume = volumeSlider.value;
        
        volumeSlider.addEventListener('input', function() {
            backgroundMusic.volume = this.value;
        });
    }
}

function showWelcomeModal() {
    document.getElementById('welcomePage').style.display = 'flex';
    
    // 播放语音欢迎
    setTimeout(() => {
        if ('speechSynthesis' in window) {
            const welcomeUtterance = new SpeechSynthesisUtterance();
            welcomeUtterance.text = "欢迎巫师的到来，魔法画图室已为您开启";
            welcomeUtterance.lang = 'zh-CN';
            welcomeUtterance.rate = 0.8;
            welcomeUtterance.pitch = 1.0;
            welcomeUtterance.volume = 0.9;
            speechSynthesis.speak(welcomeUtterance);
        }
    }, 500); // 延迟500ms播放，让页面完全加载
}

function enterApp() {
    // 停止背景音乐
    const backgroundMusic = document.getElementById('backgroundMusic');
    if (backgroundMusic) {
        backgroundMusic.pause();
        backgroundMusic.currentTime = 0;
    }
    
    // 开始过渡动画序列
    startTransitionSequence();
}

// 过渡动画序列函数
function startTransitionSequence() {
    const welcomePage = document.getElementById('welcomePage');
    const mainApp = document.getElementById('mainApp');
    const label2Effect = document.getElementById('label2Effect');
    
    // 第一步：显示标签2特效
    setTimeout(() => {
        if (label2Effect) {
            label2Effect.classList.add('animate');
        }
    }, 100);
    
    // 第二步：标签2开始放大时，欢迎页面开始淡出
    setTimeout(() => {
        welcomePage.classList.add('fade-out');
    }, 300);
    
    // 第三步：等待标签2在2秒内完全放大到10倍后，立即切换到主界面
    setTimeout(() => {
        // 标签2动画完成（2秒），现在切换到主界面
        welcomePage.style.display = 'none';
        mainApp.classList.remove('hidden');
        mainApp.classList.add('fade-in');
        
        // 标签2特效完成后隐藏
        if (label2Effect) {
            label2Effect.classList.remove('animate');
            label2Effect.style.display = 'none';
        }
        
        // 移除主界面的淡入动画类
        setTimeout(() => {
            mainApp.classList.remove('fade-in');
        }, 1000);
    }, 2100); // 等待2.1秒，确保标签2完全放大
}

function updateColor(e) {
    currentColor = e.target.value;
    // 立即更新画笔颜色
    if (!isEraser) {
        ctx.strokeStyle = currentColor;
    }
}

function updateBrushSize(e) {
    currentSize = parseInt(e.target.value);
    document.getElementById('brushSizeValue').textContent = currentSize;
    // 立即更新画笔大小
    if (!isEraser) {
        ctx.lineWidth = currentSize;
    }
}

function updateEraserSize(e) {
    eraserSize = parseInt(e.target.value);
    document.getElementById('eraserSizeValue').textContent = eraserSize;
}

// 画笔下拉菜单功能
function toggleBrushDropdown() {
    const dropdown = document.getElementById('brushDropdownContent');
    const sizeControl = document.getElementById('brushSizeControl');
    
    dropdown.classList.toggle('show');
    sizeControl.classList.toggle('show');
}

function selectBrushType(e) {
    const brushType = e.target.dataset.type;
    currentBrushType = brushType;
    
    // 更新按钮文本
    const btn = document.getElementById('brushDropdownBtn');
    const brushNames = {
        'normal': '🖌️ 普通画笔',
        'pencil': '✏️ 铅笔',
        'marker': '🖍️ 马克笔',
        'crayon': '🖍️ 蜡笔',
        'airbrush': '🎨 喷枪'
    };
    btn.textContent = brushNames[brushType] || '🖌️ 画笔';
    
    // 更新选中状态
    document.querySelectorAll('.brush-option').forEach(option => {
        option.classList.remove('active');
    });
    e.target.classList.add('active');
    
    // 关闭下拉菜单
    document.getElementById('brushDropdownContent').classList.remove('show');
    
    // 切换到画笔模式
    isEraser = false;
    currentShape = null;
    isDrawingShape = false;
    
    showNotification(`已切换到${getBrushTypeName(brushType)}`);
}

function getBrushTypeName(type) {
    const brushNames = {
        'normal': '普通画笔',
        'pencil': '铅笔',
        'marker': '马克笔',
        'crayon': '蜡笔',
        'airbrush': '喷枪'
    };
    return brushNames[type] || '普通画笔';
}

// 橡皮下拉菜单功能
function toggleEraserDropdown() {
    const dropdown = document.getElementById('eraserDropdownContent');
    const sizeControl = document.getElementById('eraserSizeControl');
    
    dropdown.classList.toggle('show');
    sizeControl.classList.toggle('show');
}

function selectEraserAction(e) {
    const action = e.target.dataset.action;
    
    if (action === 'eraser') {
        // 切换到橡皮擦模式
        isEraser = true;
        currentShape = null;
        isDrawingShape = false;
        document.getElementById('eraserDropdownBtn').textContent = '🧽 橡皮擦';
        showNotification('已切换到橡皮擦模式');
    } else if (action === 'clear') {
        // 清空画布
        clearCanvas();
    }
    
    // 更新选中状态
    document.querySelectorAll('.eraser-option').forEach(option => {
        option.classList.remove('active');
    });
    e.target.classList.add('active');
    
    // 关闭下拉菜单
    document.getElementById('eraserDropdownContent').classList.remove('show');
}

// 形状工具功能
function toggleShapeDropdown() {
    const dropdown = document.getElementById('shapeDropdownContent');
    const sizeControl = document.getElementById('shapeSizeControl');
    
    dropdown.classList.toggle('show');
    sizeControl.classList.toggle('show');
}

function selectShape(e) {
    const shape = e.target.dataset.shape;
    currentShape = shape;
    isEraser = false;
    isDrawingShape = false; // 重置绘制状态，等待第一次点击
    
    // 更新按钮文本
    const btn = document.getElementById('shapeDropdownBtn');
    const shapeNames = {
        'rectangle': '⬜ 矩形',
        'circle': '⭕ 圆形',
        'triangle': '🔺 三角形',
        'line': '➖ 直线',
        'arrow': '➡️ 箭头',
        'star': '⭐ 五角星',
        'heart': '❤️ 心形',
        'diamond': '💎 菱形'
    };
    btn.textContent = shapeNames[shape] || '🔷 形状';
    
    // 更新选中状态
    document.querySelectorAll('.shape-option').forEach(option => {
        option.classList.remove('active');
    });
    e.target.classList.add('active');
    
    // 关闭下拉菜单
    document.getElementById('shapeDropdownContent').classList.remove('show');
    
    showNotification(`已选择${shapeNames[shape]}工具，点击画布开始绘制`);
}

function updateShapeSize(e) {
    shapeSize = parseInt(e.target.value);
    document.getElementById('shapeSizeValue').textContent = shapeSize;
}

// 删除旧的橡皮擦函数，使用新的下拉菜单功能

function clearCanvas() {
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 清空导入的图片
    importedImages = [];
    
    // 清空画布后保存状态
    saveCanvasState();
}

async function saveImage() {
    try {
        console.log('开始保存图片...');
        
        // 检查画布是否存在
        if (!canvas) {
            throw new Error('画布未初始化');
        }
        
        // 显示保存中提示
        showNotification('正在保存图片...', 'info');
        
        // 延迟一下让用户看到提示
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 创建临时画布
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = canvas.width;
        tempCanvas.height = canvas.height;
        const tempCtx = tempCanvas.getContext('2d');
        
        // 设置白色背景
        tempCtx.fillStyle = '#ffffff';
        tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
        
        // 绘制当前画布内容
        tempCtx.drawImage(canvas, 0, 0);
        
        // 绘制导入的图片（如果有的话）
        if (importedImages && importedImages.length > 0) {
            importedImages.forEach((img, index) => {
                try {
                    if (img && img.element && img.element.complete) {
                        tempCtx.drawImage(img.element, img.x, img.y, img.width, img.height);
                        
                        // 为图纸类型添加边框
                        if (img.type === 'template') {
                            tempCtx.strokeStyle = '#d4af37';
                            tempCtx.lineWidth = 3;
                            tempCtx.strokeRect(img.x, img.y, img.width, img.height);
                        }
                        
                        // 为选中的图片添加高亮边框
                        if (index === selectedImageIndex) {
                            tempCtx.strokeStyle = '#ff0000';
                            tempCtx.lineWidth = 2;
                            tempCtx.setLineDash([5, 5]);
                            tempCtx.strokeRect(img.x - 2, img.y - 2, img.width + 4, img.height + 4);
                            tempCtx.setLineDash([]);
                        }
                    }
                } catch (imgError) {
                    console.warn('绘制图片时出错:', imgError);
                }
            });
        }
        
        // 生成文件名
        const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
        const filename = `霍格沃茨魔法画作_${timestamp}.png`;
        
        // 生成数据URL
        const dataURL = tempCanvas.toDataURL('image/png');
        
        // 方法1：使用Blob和URL.createObjectURL（推荐）
        try {
            // 将dataURL转换为Blob
            const byteString = atob(dataURL.split(',')[1]);
            const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
            const ab = new ArrayBuffer(byteString.length);
            const ia = new Uint8Array(ab);
            for (let i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            const blob = new Blob([ab], { type: mimeString });
            
            // 创建下载链接
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            link.style.display = 'none';
            
            // 添加到DOM并触发下载
            document.body.appendChild(link);
            link.click();
            
            // 清理
            setTimeout(() => {
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            }, 100);
            
            console.log('图片保存成功（Blob方法）:', filename);
            showNotification('图片保存成功！', 'success');
            return;
            
        } catch (blobError) {
            console.warn('Blob方法失败，尝试备用方法:', blobError);
        }
        
        // 方法2：备用方法 - 直接使用dataURL
        try {
            const link = document.createElement('a');
            link.download = filename;
            link.href = dataURL;
            link.style.display = 'none';
            
            document.body.appendChild(link);
            link.click();
            
            setTimeout(() => {
                document.body.removeChild(link);
            }, 100);
            
            console.log('图片保存成功（备用方法）:', filename);
            showNotification('图片保存成功！', 'success');
            
        } catch (fallbackError) {
            console.error('备用方法也失败:', fallbackError);
            throw new Error('所有保存方法都失败了');
        }
        
    } catch (error) {
        console.error('保存图片失败:', error);
        showNotification('保存失败：' + error.message, 'error');
    }
}

// 更新绘画模式指示器（现在显示当前状态）
function updatePaintingModeIndicator() {
    const indicator = document.getElementById('paintingModeIndicator');
    if (indicator) {
        indicator.innerHTML = '<span>🎨 绘画工具: 就绪</span>';
        indicator.classList.remove('active');
    }
}

function startDrawing(e) {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // 检查是否点击在图片上
    const imageInfo = getImageAtPosition(x, y);
    if (imageInfo) {
        // 如果点击在图片上，不开始绘画
        return;
    }
    
    // 开始绘画或绘制形状
    if (currentShape && !isDrawingShape) {
        // 第一次点击：开始绘制形状
        isDrawingShape = true;
        shapeStartX = x;
        shapeStartY = y;
        // 设置画布样式
        ctx.strokeStyle = currentColor;
        ctx.fillStyle = currentColor;
        ctx.lineWidth = currentSize;
        console.log('开始绘制形状');
    } else if (isDrawingShape && currentShape) {
        // 第二次点击：完成绘制形状
        const endX = x;
        const endY = y;
        drawShape(endX, endY);
        isDrawingShape = false;
        // 保存画布状态
        saveCanvasState();
        console.log('完成绘制形状');
    } else {
        // 普通绘画模式
        isDrawing = true;
        lastX = x;
        lastY = y;
    }
    
    // 确保画笔设置正确
    if (isEraser) {
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = eraserSize;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
    } else {
        // 根据画笔类型设置
        ctx.strokeStyle = currentColor;
        ctx.lineWidth = currentSize;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
    }
    
    console.log('开始绘画');
}

function draw(e) {
    if (!isDrawing && !isDrawingShape) return;
    
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    if (isDrawingShape && currentShape) {
        // 绘制形状模式 - 拖动时实时预览
        previewShape(x, y);
    } else if (isDrawing) {
        if (isEraser) {
            // 橡皮擦模式
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = eraserSize;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.stroke();
        } else {
            // 画笔模式 - 根据画笔类型绘制
            drawWithBrushType(lastX, lastY, x, y);
        }
        
        lastX = x;
        lastY = y;
    }
}

// 根据画笔类型绘制
function drawWithBrushType(startX, startY, endX, endY) {
    switch (currentBrushType) {
        case 'normal':
            drawNormalBrush(startX, startY, endX, endY);
            break;
        case 'pencil':
            drawPencilBrush(startX, startY, endX, endY);
            break;
        case 'marker':
            drawMarkerBrush(startX, startY, endX, endY);
            break;
        case 'crayon':
            drawCrayonBrush(startX, startY, endX, endY);
            break;
        case 'airbrush':
            drawAirbrushBrush(startX, startY, endX, endY);
            break;
        default:
            drawNormalBrush(startX, startY, endX, endY);
    }
}

// 普通画笔
function drawNormalBrush(startX, startY, endX, endY) {
    ctx.strokeStyle = currentColor;
    ctx.lineWidth = currentSize;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
}

// 铅笔效果
function drawPencilBrush(startX, startY, endX, endY) {
    ctx.strokeStyle = currentColor;
    ctx.lineWidth = currentSize;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    
    // 铅笔效果：稍微透明的线条
    ctx.globalAlpha = 0.7;
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
    
    // 添加一些随机的铅笔痕迹
    const distance = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
    const steps = Math.floor(distance / 3);
    
    for (let i = 0; i < steps; i++) {
        const t = i / steps;
        const x = startX + (endX - startX) * t;
        const y = startY + (endY - startY) * t;
        
        if (Math.random() < 0.3) {
            ctx.globalAlpha = 0.3;
            ctx.beginPath();
            ctx.arc(x + (Math.random() - 0.5) * 2, y + (Math.random() - 0.5) * 2, 1, 0, Math.PI * 2);
            ctx.fill();
        }
    }
    
    ctx.globalAlpha = 1.0;
}

// 马克笔效果
function drawMarkerBrush(startX, startY, endX, endY) {
    ctx.strokeStyle = currentColor;
    ctx.lineWidth = currentSize * 1.5;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    
    // 马克笔效果：更粗的线条，稍微透明
    ctx.globalAlpha = 0.8;
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
    
    // 添加边缘效果
    ctx.globalAlpha = 0.4;
    ctx.lineWidth = currentSize * 2;
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
    
    ctx.globalAlpha = 1.0;
}

// 蜡笔效果
function drawCrayonBrush(startX, startY, endX, endY) {
    // 蜡笔效果：粗糙的纹理
    const distance = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
    const steps = Math.floor(distance / 2);
    
    for (let i = 0; i < steps; i++) {
        const t = i / steps;
        const x = startX + (endX - startX) * t;
        const y = startY + (endY - startY) * t;
        
        // 随机大小的点
        const size = currentSize * (0.5 + Math.random() * 0.5);
        ctx.globalAlpha = 0.6 + Math.random() * 0.4;
        
        ctx.fillStyle = currentColor;
        ctx.beginPath();
        ctx.arc(x + (Math.random() - 0.5) * 3, y + (Math.random() - 0.5) * 3, size, 0, Math.PI * 2);
        ctx.fill();
    }
    
    ctx.globalAlpha = 1.0;
}

// 喷枪效果
function drawAirbrushBrush(startX, startY, endX, endY) {
    // 喷枪效果：渐变扩散
    const distance = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
    const steps = Math.floor(distance / 1.5);
    
    for (let i = 0; i < steps; i++) {
        const t = i / steps;
        const x = startX + (endX - startX) * t;
        const y = startY + (endY - startY) * t;
        
        // 创建渐变效果
        const gradient = ctx.createRadialGradient(x, y, 0, x, y, currentSize * 2);
        gradient.addColorStop(0, currentColor);
        gradient.addColorStop(0.5, currentColor + '80');
        gradient.addColorStop(1, currentColor + '00');
        
        ctx.fillStyle = gradient;
        ctx.globalAlpha = 0.3;
        
        ctx.beginPath();
        ctx.arc(x, y, currentSize * 2, 0, Math.PI * 2);
        ctx.fill();
    }
    
    ctx.globalAlpha = 1.0;
}

function stopDrawing(e) {
    // 停止绘画（松开鼠标）
    if (isDrawing) {
        isDrawing = false;
        console.log('停止绘画');
        
        // 保存画布状态
        saveCanvasState();
    }
    
    // 形状绘制不需要在这里处理，在startDrawing中处理第二次点击
}

// 图片点击计数器
let imageClickCount = 0;
let imageClickTimer = null;
let lastClickedImageIndex = -1;

// 图片点击处理函数
function handleImageClick(e) {
    // 如果正在绘画，不处理图片点击
    if (isDrawing || isDrawingShape) {
        return;
    }
    
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // 检查是否点击在图片上
    const imageInfo = getImageAtPosition(x, y);
    if (imageInfo) {
        const img = imageInfo.image;
        const currentImageIndex = imageInfo.index;
        
        // 如果点击的是不同的图片，重置计数器
        if (currentImageIndex !== lastClickedImageIndex) {
            imageClickCount = 0;
            lastClickedImageIndex = currentImageIndex;
        }
        
        // 设置当前选中的图片
        selectedImageIndex = currentImageIndex;
        
        // 增加点击计数
        imageClickCount++;
        
        // 清除之前的定时器
        if (imageClickTimer) {
            clearTimeout(imageClickTimer);
        }
        
        // 设置新的定时器
        imageClickTimer = setTimeout(() => {
            handleImageClickAction(imageClickCount, img);
            imageClickCount = 0;
            imageClickTimer = null;
        }, 300); // 300ms内检测多次点击
        
        e.preventDefault();
        e.stopPropagation();
    }
}

// 处理图片点击动作
function handleImageClickAction(clickCount, img) {
    console.log(`图片被点击 ${clickCount} 次`);
    
    const scaleRatio = (img.width / img.originalWidth).toFixed(1);
    
    switch (clickCount) {
        case 1:
            // 单击：选中图片
            showNotification(`图片已选中 (缩放: ${scaleRatio}x) - 按Delete键删除`, 'info');
            break;
        case 2:
            // 双击：放大图片
            if (img.width < img.originalWidth * 3) {
                img.width *= 1.5;
                img.height *= 1.5;
                const newScaleRatio = (img.width / img.originalWidth).toFixed(1);
                showNotification(`图片已放大 (缩放: ${newScaleRatio}x)`, 'success');
            } else {
                showNotification('图片已达到最大尺寸 (3x)', 'warning');
            }
            break;
        case 3:
            // 三击：缩小图片
            if (img.width > img.originalWidth * 0.5) {
                img.width /= 1.5;
                img.height /= 1.5;
                const newScaleRatio = (img.width / img.originalWidth).toFixed(1);
                showNotification(`图片已缩小 (缩放: ${newScaleRatio}x)`, 'success');
            } else {
                showNotification('图片已达到最小尺寸 (0.5x)', 'warning');
            }
            break;
        default:
            // 更多点击：恢复原始大小
            img.width = img.originalWidth;
            img.height = img.originalHeight;
            showNotification('图片已恢复原始大小 (1.0x)', 'info');
            break;
    }
    
    redrawCanvas();
}

// 删除选中的图片
function deleteSelectedImage() {
    if (selectedImageIndex >= 0 && selectedImageIndex < importedImages.length) {
        const deletedImage = importedImages[selectedImageIndex];
        const imageName = deletedImage.element.alt || '图片';
        
        // 显示确认对话框
        const confirmMessage = `确定要删除选中的${imageName}吗？\n\n此操作无法撤销。`;
        if (confirm(confirmMessage)) {
            // 从数组中删除图片
            importedImages.splice(selectedImageIndex, 1);
            
            // 重置选中索引
            selectedImageIndex = -1;
            
            // 重绘画布
            redrawCanvas();
            
            // 保存画布状态
            saveCanvasState();
            
            // 更新图片计数器
            updateImageCounter();
            
            // 显示成功通知
            showNotification(`${imageName}已删除`, 'success');
            
            console.log('图片删除成功');
        } else {
            console.log('用户取消删除操作');
        }
    } else {
        showNotification('没有选中的图片', 'warning');
    }
}

// 更新图片计数器
function updateImageCounter() {
    const counterElement = document.getElementById('imageCounter');
    if (counterElement) {
        const counterText = counterElement.querySelector('.counter-text');
        if (counterText) {
            counterText.textContent = importedImages.length;
            
            // 根据图片数量改变颜色
            if (importedImages.length === 0) {
                counterText.style.color = '#888888';
            } else if (importedImages.length <= 3) {
                counterText.style.color = '#4CAF50';
            } else if (importedImages.length <= 6) {
                counterText.style.color = '#FF9800';
            } else {
                counterText.style.color = '#f44336';
            }
        }
    }
}

// 删除所有图片
function deleteAllImages() {
    if (importedImages.length === 0) {
        showNotification('画布上没有图片', 'info');
        return;
    }
    
    const confirmMessage = `确定要删除画布上的所有图片吗？\n\n共${importedImages.length}张图片，此操作无法撤销。`;
    if (confirm(confirmMessage)) {
        // 清空图片数组
        importedImages = [];
        
        // 重置选中索引
        selectedImageIndex = -1;
        
        // 重绘画布
        redrawCanvas();
        
        // 保存画布状态
        saveCanvasState();
        
        // 更新图片计数器
        updateImageCounter();
        
        // 显示成功通知
        showNotification('所有图片已删除', 'success');
        
        console.log('所有图片删除成功');
    } else {
        console.log('用户取消删除所有图片操作');
    }
}

// 触摸设备事件处理
function handleTouch(e) {
    e.preventDefault();
    const touch = e.touches[0];
    
    if (e.type === 'touchstart') {
        // 触摸开始，模拟鼠标按下
        const mouseEvent = new MouseEvent('mousedown', {
            clientX: touch.clientX,
            clientY: touch.clientY
        });
        canvas.dispatchEvent(mouseEvent);
    } else if (e.type === 'touchmove') {
        // 触摸移动，模拟鼠标移动
        const mouseEvent = new MouseEvent('mousemove', {
            clientX: touch.clientX,
            clientY: touch.clientY
        });
        canvas.dispatchEvent(mouseEvent);
    } else if (e.type === 'touchend') {
        // 触摸结束，模拟鼠标松开
        const mouseEvent = new MouseEvent('mouseup', {
            clientX: touch.clientX,
            clientY: touch.clientY
        });
        canvas.dispatchEvent(mouseEvent);
    }
}

// 手部追踪功能
function initializeHandTracking() {
    hands = new Hands({
        locateFile: (file) => {
            return `https://cdn.jsdelivr.net/npm/@mediapipe/hands@0.4.1646424915/${file}`;
        }
    });
    
    hands.setOptions({
        maxNumHands: 1,
        modelComplexity: 1,
        minDetectionConfidence: 0.5,
        minTrackingConfidence: 0.5
    });
    
    hands.onResults(onHandResults);
}

function toggleCamera() {
    if (isHandTracking) {
        stopCamera();
    } else {
        startCamera();
    }
}

function startCamera() {
    cameraUtils = new Camera(video, {
        onFrame: async () => {
            await hands.send({image: video});
        },
        width: 300,
        height: 200
    });
    cameraUtils.start();
    isHandTracking = true;
    document.getElementById('toggleCamera').textContent = '关闭手部追踪';
}

function stopCamera() {
    if (cameraUtils) {
        cameraUtils.stop();
    }
    isHandTracking = false;
    document.getElementById('toggleCamera').textContent = '开启手部追踪';
    handCtx.clearRect(0, 0, handCanvas.width, handCanvas.height);
}

function onHandResults(results) {
    handCtx.clearRect(0, 0, handCanvas.width, handCanvas.height);
    
    if (results.multiHandLandmarks) {
        for (const landmarks of results.multiHandLandmarks) {
            drawConnectors(handCtx, landmarks, HAND_CONNECTIONS, {color: '#00FF00', lineWidth: 2});
            drawLandmarks(handCtx, landmarks, {color: '#FF0000', lineWidth: 1, radius: 3});
            
            if (isHandDrawing) {
                handleHandDrawing(landmarks);
            }
        }
    }
}

function handleHandDrawing(landmarks) {
    const thumb = landmarks[4];  // 大拇指尖
    const indexFinger = landmarks[8];  // 食指尖
    const middleFinger = landmarks[12];  // 中指尖
    const ringFinger = landmarks[16];  // 无名指尖
    const pinky = landmarks[20];  // 小指尖
    
    // 计算手指之间的距离
    const thumbIndexDistance = Math.sqrt(
        Math.pow(thumb.x - indexFinger.x, 2) + 
        Math.pow(thumb.y - indexFinger.y, 2)
    );
    
    // 检查其他手指是否弯曲
    const middleExtended = middleFinger.y < landmarks[10].y;
    const ringExtended = ringFinger.y < landmarks[14].y;
    const pinkyExtended = pinky.y < landmarks[18].y;
    
    // 大拇指和食指并拢，其他手指弯曲 - 绘画模式
    const pinchThreshold = 0.05 * appSettings.trackingSensitivity; // 根据灵敏度调整
    
        if (thumbIndexDistance < pinchThreshold && !middleExtended && !ringExtended && !pinkyExtended) {
            // 使用食指位置进行绘画
            const x = indexFinger.x * canvas.width;
            const y = indexFinger.y * canvas.height;
            
            if (!isDrawing) {
                isDrawing = true;
                lastX = x;
                lastY = y;
            } else {
                // 使用新的画笔类型绘制
                if (isEraser) {
                    ctx.strokeStyle = '#ffffff';
                    ctx.lineWidth = eraserSize;
                    ctx.lineCap = 'round';
                    ctx.lineJoin = 'round';
                    
                    ctx.beginPath();
                    ctx.moveTo(lastX, lastY);
                    ctx.lineTo(x, y);
                    ctx.stroke();
                } else {
                    drawWithBrushType(lastX, lastY, x, y);
                }
                
                lastX = x;
                lastY = y;
            }
        } else {
            isDrawing = false;
        }
}

function toggleDrawingMode() {
    isHandDrawing = !isHandDrawing;
    const btn = document.getElementById('toggleDrawing');
    const modeText = document.getElementById('modeText');
    
    if (isHandDrawing) {
        btn.textContent = '切换到鼠标模式';
        modeText.textContent = '手部追踪绘画模式';
    } else {
        btn.textContent = '切换到手部模式';
        modeText.textContent = '鼠标绘画模式';
    }
}

// 咒语功能
function generateSpellsInterface() {
    const spellsGrid = document.querySelector('.spells-grid');
    if (!spellsGrid) return;
    
    spellsGrid.innerHTML = '';
    
    spells.forEach(spell => {
        const spellCard = document.createElement('div');
        spellCard.className = `spell-card ${spell.forbidden ? 'forbidden' : ''}`;
        spellCard.innerHTML = `
            <div class="spell-name">${spell.name}</div>
            <div class="spell-pronunciation">${spell.pronunciation}</div>
            <div class="spell-description">${spell.description}</div>
            <button class="spell-info-btn" onclick="showSpellInfo('${spell.name}')">详细信息</button>
        `;
        
        spellCard.addEventListener('click', () => castSpell(spell));
        spellsGrid.appendChild(spellCard);
    });
}

function castSpell(spell) {
    createSpellEffect(spell.effect);
    showSpellNotification(spell.name);
    speakSpell(spell);
}

function speakSpell(spell) {
    if ('speechSynthesis' in window && appSettings.voiceEnabled) {
        const utterance = new SpeechSynthesisUtterance();
        utterance.text = `${spell.name}. ${spell.description}`;
        utterance.lang = 'zh-CN';
        utterance.rate = 0.8;
        utterance.pitch = 1.0;
        utterance.volume = appSettings.voiceVolume;
        speechSynthesis.speak(utterance);
    }
}

function createSpellEffect(effectType) {
    const effectContainer = document.getElementById('spellEffects');
    const effect = document.createElement('div');
    effect.className = 'spell-effect';
    
    switch (effectType) {
        case 'light':
            effect.style.background = 'radial-gradient(circle, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0.4) 50%, transparent 100%)';
            break;
        case 'fire':
            effect.style.background = 'radial-gradient(circle, rgba(255,69,0,0.8) 0%, rgba(255,140,0,0.6) 50%, transparent 100%)';
            break;
        case 'water':
            effect.style.background = 'radial-gradient(circle, rgba(0,191,255,0.6) 0%, rgba(135,206,235,0.4) 50%, transparent 100%)';
            break;
        case 'patronus':
            effect.style.background = 'radial-gradient(circle, rgba(255,255,255,0.9) 0%, rgba(173,216,230,0.7) 50%, transparent 100%)';
            break;
        case 'kill':
            effect.style.background = 'radial-gradient(circle, rgba(255,0,0,0.8) 0%, rgba(139,0,0,0.6) 50%, transparent 100%)';
            break;
        default:
            effect.style.background = 'radial-gradient(circle, rgba(212,175,55,0.6) 0%, rgba(255,215,0,0.4) 50%, transparent 100%)';
    }
    
    effectContainer.appendChild(effect);
    
    setTimeout(() => {
        effect.remove();
    }, 3000);
}

function showSpellNotification(spellName) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(45deg, #d4af37, #ffd700);
        color: #2c1810;
        padding: 15px 25px;
        border-radius: 10px;
        font-weight: bold;
        z-index: 1001;
        animation: slideIn 0.5s ease-out;
    `;
    notification.textContent = `施放咒语: ${spellName}`;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

function showSpellInfo(spellName) {
    const spell = spells.find(s => s.name === spellName);
    if (spell) {
        alert(`${spell.name}\n发音: ${spell.pronunciation}\n描述: ${spell.description}\n${spell.forbidden ? '⚠️ 这是不可饶恕咒！' : ''}`);
    }
}

function showSpellsModal() {
    document.getElementById('spellsModal').style.display = 'flex';
}

function closeSpellsModal() {
    document.getElementById('spellsModal').style.display = 'none';
}

// 图纸功能
function generateTemplatesInterface() {
    const templatesContainer = document.querySelector('.templates-categories');
    if (!templatesContainer) return;
    
    templatesContainer.innerHTML = '';
    
    Object.entries(templates).forEach(([category, items]) => {
        const categoryDiv = document.createElement('div');
        categoryDiv.className = 'category';
        categoryDiv.innerHTML = `
            <div class="category-title">${category}</div>
            <div class="templates-grid expanded">
                ${items.map(item => `
                    <div class="template-item" onclick="loadTemplate('${item.name}')">
                        <img src="${item.image}" alt="${item.name}">
                        <div class="template-name">${item.name}</div>
                    </div>
                `).join('')}
            </div>
        `;
        templatesContainer.appendChild(categoryDiv);
    });
}

function toggleCategory(element) {
    const grid = element.nextElementSibling;
    grid.classList.toggle('expanded');
}

function loadTemplate(templateName) {
    // 查找对应的图纸数据
    let templateImage = null;
    for (const [category, items] of Object.entries(templates)) {
        const item = items.find(item => item.name === templateName);
        if (item) {
            templateImage = item.image;
            break;
        }
    }
    
    if (templateImage) {
        // 创建图片对象
        const img = new Image();
        img.onload = function() {
            // 计算图片在画布左上角的显示尺寸
            const maxWidth = 200; // 最大宽度
            const maxHeight = 150; // 最大高度
            
            let displayWidth = img.width;
            let displayHeight = img.height;
            
            // 按比例缩放
            if (displayWidth > maxWidth) {
                const ratio = maxWidth / displayWidth;
                displayWidth = maxWidth;
                displayHeight = displayHeight * ratio;
            }
            
            if (displayHeight > maxHeight) {
                const ratio = maxHeight / displayHeight;
                displayHeight = maxHeight;
                displayWidth = displayWidth * ratio;
            }
            
            // 创建图片对象，添加到可移动图片数组中
            const imageObj = {
                element: img,
                x: 20, // 左边距
                y: 20, // 上边距
                width: displayWidth,
                height: displayHeight,
                originalWidth: img.width,
                originalHeight: img.height,
                isSelected: false,
                isDragging: false,
                dragStartX: 0,
                dragStartY: 0,
                type: 'template', // 标记为图纸类型
                name: templateName
            };
            
            // 添加新图片（不清除原有图片）
            importedImages.push(imageObj);
            selectedImageIndex = importedImages.length - 1; // 选中新导入的图片
            
            // 重绘画布
            redrawCanvas();
            
            // 更新图片计数器
            updateImageCounter();
            
            // 显示成功消息
            showNotification(`图纸 "${templateName}" 已加载到画布左上角，点击图片进行移动，双击放大，Delete删除`);
        };
        
        img.onerror = function() {
            showNotification(`加载图纸失败: ${templateName}`);
        };
        
        img.src = templateImage;
    } else {
        showNotification(`未找到图纸: ${templateName}`);
    }
}

function showTemplatesModal() {
    document.getElementById('templatesModal').style.display = 'flex';
}

function closeTemplatesModal() {
    document.getElementById('templatesModal').style.display = 'none';
}

// 设置功能
function showSettings() {
    document.getElementById('settingsPanel').style.display = 'flex';
    loadSettingsToUI();
}

function closeSettings() {
    document.getElementById('settingsPanel').style.display = 'none';
}

function bindSettingsEvents() {
    // 设置面板中的控件事件
    document.getElementById('defaultBrushSize').addEventListener('input', function() {
        document.getElementById('defaultBrushSizeValue').textContent = this.value;
    });
    
    document.getElementById('voiceVolume').addEventListener('input', function() {
        document.getElementById('voiceVolumeValue').textContent = this.value;
    });
    
    document.getElementById('voiceSensitivity').addEventListener('input', function() {
        document.getElementById('voiceSensitivityValue').textContent = this.value;
    });
    
    document.getElementById('autoStopTime').addEventListener('input', function() {
        document.getElementById('autoStopTimeValue').textContent = this.value;
    });
}

function loadSettingsToUI() {
    document.getElementById('defaultBrushSize').value = appSettings.defaultBrushSize;
    document.getElementById('defaultBrushSizeValue').textContent = appSettings.defaultBrushSize;
    document.getElementById('defaultColor').value = appSettings.defaultColor;
    document.getElementById('voiceEnabled').checked = appSettings.voiceEnabled;
    document.getElementById('voiceVolume').value = appSettings.voiceVolume;
    document.getElementById('voiceVolumeValue').textContent = appSettings.voiceVolume;
    document.getElementById('speechRecognitionEnabled').checked = appSettings.speechRecognitionEnabled;
    document.getElementById('recognitionLanguage').value = appSettings.recognitionLanguage;
    document.getElementById('voiceSensitivity').value = appSettings.voiceSensitivity;
    document.getElementById('voiceSensitivityValue').textContent = appSettings.voiceSensitivity;
    document.getElementById('autoStopTime').value = appSettings.autoStopTime;
    document.getElementById('autoStopTimeValue').textContent = appSettings.autoStopTime;
}

function saveSettings() {
    appSettings.defaultBrushSize = parseInt(document.getElementById('defaultBrushSize').value);
    appSettings.defaultColor = document.getElementById('defaultColor').value;
    appSettings.voiceEnabled = document.getElementById('voiceEnabled').checked;
    appSettings.voiceVolume = parseFloat(document.getElementById('voiceVolume').value);
    appSettings.speechRecognitionEnabled = document.getElementById('speechRecognitionEnabled').checked;
    appSettings.recognitionLanguage = document.getElementById('recognitionLanguage').value;
    appSettings.voiceSensitivity = parseFloat(document.getElementById('voiceSensitivity').value);
    appSettings.autoStopTime = parseInt(document.getElementById('autoStopTime').value);
    
    // 保存到本地存储
    localStorage.setItem('hogwartsSettings', JSON.stringify(appSettings));
    
    // 应用设置
    applySettings();
    
    closeSettings();
    showNotification('设置已保存！');
}

function resetSettings() {
    appSettings = {
        defaultBrushSize: 5,
        defaultColor: '#000000',
        voiceEnabled: true,
        voiceVolume: 0.8,
        speechRecognitionEnabled: false,
        recognitionLanguage: 'zh-CN',
        voiceSensitivity: 0.7,
        autoStopTime: 15
    };
    
    loadSettingsToUI();
    applySettings();
    showNotification('设置已重置！');
}

function applySettings() {
    currentSize = appSettings.defaultBrushSize;
    currentColor = appSettings.defaultColor;
    document.getElementById('brushSize').value = currentSize;
    document.getElementById('brushSizeValue').textContent = currentSize;
    document.getElementById('colorPicker').value = currentColor;
    
    // 应用语音识别设置
    if (appSettings.speechRecognitionEnabled) {
        if (recognition && !isListening) {
            startSpeechRecognition();
        }
    } else {
        if (recognition && isListening) {
            stopSpeechRecognition();
        }
    }
}

// 语音识别功能
function initializeSpeechRecognition() {
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
        recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
        recognition.continuous = true;
        recognition.interimResults = false; // 只显示最终结果
        recognition.lang = appSettings.recognitionLanguage;
        recognition.maxAlternatives = 1;
        
        // 设置只接受麦克风输入
        if (recognition.audioSource !== undefined) {
            recognition.audioSource = 'microphone';
        }
        
        recognition.onstart = function() {
            console.log('语音识别已启动');
            isListening = true;
            updateVoiceButton(true);
        };
        
        recognition.onresult = function(event) {
            const transcript = event.results[event.results.length - 1][0].transcript;
            console.log('识别到语音:', transcript);
            
            // 检查是否匹配咒语
            const matchedSpell = findSpellByVoice(transcript);
            if (matchedSpell) {
                console.log('匹配到咒语:', matchedSpell.name);
                // 在画布中央显示咒语名称，保留2秒后消失
                displaySpellOnCanvas(matchedSpell.name);
                // 施放咒语效果
                castSpell(matchedSpell);
                showSpellNotification(`语音识别成功！施放咒语: ${matchedSpell.name}`);
            } else {
                // 如果没有匹配到咒语，不显示任何内容
                console.log('未匹配到咒语，忽略');
            }
        };
        
        recognition.onerror = function(event) {
            console.error('语音识别错误:', event.error);
            if (event.error === 'no-speech') {
                // 没有检测到语音，继续监听
                if (isListening) {
                    setTimeout(() => {
                        if (isListening) recognition.start();
                    }, 100);
                }
            } else {
                showNotification(`语音识别错误: ${event.error}`);
                stopSpeechRecognition();
            }
        };
        
        recognition.onend = function() {
            console.log('语音识别已结束');
            if (appSettings.speechRecognitionEnabled && isListening) {
                // 自动重新启动语音识别
                setTimeout(() => {
                    if (isListening) recognition.start();
                }, 100);
            }
        };
    } else {
        console.error('浏览器不支持语音识别');
        showNotification('您的浏览器不支持语音识别功能');
    }
}

function updateVoiceButton(isListening) {
    const voiceBtn = document.getElementById('voiceBtn');
    const voiceIndicator = document.getElementById('voiceIndicator');
    
    if (isListening) {
        voiceBtn.textContent = '🔴 停止检测';
        voiceBtn.style.background = 'linear-gradient(45deg, #ff0000, #ff6666)';
        voiceIndicator.style.display = 'block';
        voiceIndicator.innerHTML = '<span>🎤 正在聆听咒语...</span>';
        voiceIndicator.style.background = 'rgba(255, 0, 0, 0.8)';
        voiceIndicator.style.borderColor = '#ff0000';
    } else {
        voiceBtn.textContent = '🎤 语音检测';
        voiceBtn.style.background = 'linear-gradient(45deg, #4a2c1a, #8b4513)';
        voiceIndicator.style.display = 'none';
    }
}

function findSpellByVoice(transcript) {
    const lowerTranscript = transcript.toLowerCase().trim();
    
    // 中文咒语匹配（更宽松的匹配）
    const chineseSpellMap = {
        '荧光闪烁': 'Lumos',
        '荧光': 'Lumos',
        '闪烁': 'Lumos',
        '诺克斯': 'Nox',
        '漂浮咒': 'Wingardium Leviosa',
        '漂浮': 'Wingardium Leviosa',
        '阿拉霍洞开': 'Alohomora',
        '阿拉霍': 'Alohomora',
        '洞开': 'Alohomora',
        '守护神咒': 'Expecto Patronum',
        '守护神': 'Expecto Patronum',
        '缴械咒': 'Expelliarmus',
        '缴械': 'Expelliarmus',
        '昏迷咒': 'Stupefy',
        '昏迷': 'Stupefy',
        '防护咒': 'Protego',
        '防护': 'Protego',
        '召唤咒': 'Accio',
        '召唤': 'Accio',
        '修复咒': 'Reparo',
        '修复': 'Reparo',
        '火焰咒': 'Incendio',
        '火焰': 'Incendio',
        '清水如泉': 'Aguamenti',
        '清水': 'Aguamenti',
        '全身束缚': 'Petrificus Totalus',
        '束缚': 'Petrificus Totalus',
        '神锋无影': 'Sectumsempra',
        '神锋': 'Sectumsempra',
        '钻心剜骨': 'Crucio',
        '钻心': 'Crucio',
        '夺魂咒': 'Imperio',
        '夺魂': 'Imperio',
        '阿瓦达索命': 'Avada Kedavra',
        '阿瓦达': 'Avada Kedavra',
        '索命': 'Avada Kedavra',
        '遗忘咒': 'Obliviate',
        '遗忘': 'Obliviate',
        '滑稽滑稽': 'Riddikulus',
        '滑稽': 'Riddikulus',
        '无声无息': 'Silencio',
        '无声': 'Silencio'
    };
    
    // 英文咒语匹配（更宽松的匹配）
    const englishSpellMap = {
        'lumos': 'Lumos',
        'nox': 'Nox',
        'wingardium leviosa': 'Wingardium Leviosa',
        'leviosa': 'Wingardium Leviosa',
        'alohomora': 'Alohomora',
        'expecto patronum': 'Expecto Patronum',
        'patronum': 'Expecto Patronum',
        'expelliarmus': 'Expelliarmus',
        'stupefy': 'Stupefy',
        'protego': 'Protego',
        'accio': 'Accio',
        'reparo': 'Reparo',
        'incendio': 'Incendio',
        'aguamenti': 'Aguamenti',
        'petrificus totalus': 'Petrificus Totalus',
        'petrificus': 'Petrificus Totalus',
        'sectumsempra': 'Sectumsempra',
        'crucio': 'Crucio',
        'imperio': 'Imperio',
        'avada kedavra': 'Avada Kedavra',
        'avada': 'Avada Kedavra',
        'kedavra': 'Avada Kedavra',
        'obliviate': 'Obliviate',
        'riddikulus': 'Riddikulus',
        'silencio': 'Silencio'
    };
    
    // 模糊匹配 - 检查是否包含关键词
    for (let [key, value] of Object.entries(chineseSpellMap)) {
        if (lowerTranscript.includes(key)) {
            return spells.find(spell => spell.name === value);
        }
    }
    
    for (let [key, value] of Object.entries(englishSpellMap)) {
        if (lowerTranscript.includes(key)) {
            return spells.find(spell => spell.name === value);
        }
    }
    
    // 更宽松的匹配 - 检查部分匹配
    for (let [key, value] of Object.entries(chineseSpellMap)) {
        if (key.includes(lowerTranscript) || lowerTranscript.includes(key)) {
            return spells.find(spell => spell.name === value);
        }
    }
    
    for (let [key, value] of Object.entries(englishSpellMap)) {
        if (key.includes(lowerTranscript) || lowerTranscript.includes(key)) {
            return spells.find(spell => spell.name === value);
        }
    }
    
    return null;
}

function startSpeechRecognition() {
    if (recognition && !isListening) {
        try {
            recognition.start();
            isListening = true;
            updateVoiceButton(true);
            showNotification('语音识别已开启！请说出咒语或任意文字');
        } catch (error) {
            console.error('启动语音识别失败:', error);
            showNotification('启动语音识别失败，请重试');
        }
    }
}

function stopSpeechRecognition() {
    if (recognition && isListening) {
        try {
            recognition.stop();
            isListening = false;
            updateVoiceButton(false);
            showNotification('语音识别已关闭！');
        } catch (error) {
            console.error('停止语音识别失败:', error);
        }
    }
}

// 语音检测功能
function toggleVoiceRecognition() {
    if (isListening) {
        stopSpeechRecognition();
    } else {
        startSpeechRecognition();
    }
}

// 魔法滚轮功能
function bindMagicalWheel() {
    const wheelContainer = document.querySelector('.wheel-container');
    if (!wheelContainer) return;
    
    // 清空现有内容
    wheelContainer.innerHTML = '';
    
    // 创建第一组项目
    const items = [
        { term: "魔杖", icon: "🪄", text: "魔杖" },
        { term: "分院帽", icon: "🎩", text: "分院帽" },
        { term: "凤凰", icon: "🦅", text: "凤凰" },
        { term: "摄魂怪", icon: "👻", text: "摄魂怪" },
        { term: "魁地奇", icon: "🏈", text: "魁地奇" },
        { term: "霍格沃茨特快", icon: "🚂", text: "霍格沃茨特快" },
        { term: "活点地图", icon: "🗺️", text: "活点地图" },
        { term: "时间转换器", icon: "⏰", text: "时间转换器" },
        { term: "曼德拉草", icon: "🌱", text: "曼德拉草" },
        { term: "夜骐", icon: "🦇", text: "夜骐" }
    ];
    
    // 创建第一组项目
    items.forEach(item => {
        const wheelItem = createWheelItem(item.term, item.icon, item.text);
        wheelContainer.appendChild(wheelItem);
    });
    
    // 创建第二组项目（用于无缝滚动）
    items.forEach(item => {
        const wheelItem = createWheelItem(item.term, item.icon, item.text);
        wheelContainer.appendChild(wheelItem);
    });
}

function createWheelItem(term, icon, text) {
    const item = document.createElement('div');
    item.className = 'wheel-item';
    item.dataset.term = term;
    
    item.innerHTML = `
        <div class="magical-icon">${icon}</div>
        <div class="magical-text">${text}</div>
    `;
    
    item.addEventListener('click', function() {
        // 创建魔法效果
        createMagicalEffect(icon, text);
        
        // 显示哈利波特专有词汇解释
        showHogwartsTerm(term);
        
        // 播放音效
        if ('speechSynthesis' in window && appSettings.voiceEnabled) {
            const utterance = new SpeechSynthesisUtterance();
            utterance.text = `${text} - ${getHogwartsTermDescription(term)}`;
            utterance.lang = 'zh-CN';
            utterance.rate = 0.8;
            utterance.volume = appSettings.voiceVolume * 0.5;
            speechSynthesis.speak(utterance);
        }
    });
    
    return item;
}

// 哈利波特专有词汇数据
const hogwartsTerms = {
    "魔杖": "巫师的法器，由不同木材和杖芯制成，选择巫师而非相反",
    "分院帽": "霍格沃茨的分院工具，能看透学生内心，将其分配到合适的学院",
    "凤凰": "神奇生物，能重生，眼泪有治愈能力，羽毛可用于制作魔杖",
    "摄魂怪": "阿兹卡班的守卫，吸食快乐，让人感到绝望，最怕守护神咒",
    "魁地奇": "巫师界的运动，骑扫帚在空中进行，需要抓住金色飞贼获胜",
    "霍格沃茨特快": "连接伦敦国王十字车站和霍格沃茨的魔法列车",
    "活点地图": "显示霍格沃茨内所有人位置的魔法地图，由掠夺者制作",
    "时间转换器": "能让人回到过去的魔法物品，赫敏曾用它同时上多门课",
    "曼德拉草": "有魔力的植物，哭声能致命，成熟后可用于制作解药",
    "夜骐": "只有见过死亡的人才能看见的神奇生物，拉霍格沃茨的马车"
};

function getHogwartsTermDescription(term) {
    return hogwartsTerms[term] || "哈利波特世界中的魔法物品";
}

function showHogwartsTerm(term) {
    const description = getHogwartsTermDescription(term);
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: linear-gradient(145deg, #2c1810, #4a2c1a);
        border: 3px solid #d4af37;
        border-radius: 15px;
        padding: 20px;
        color: #f0f0f0;
        font-weight: bold;
        text-align: center;
        z-index: 1002;
        max-width: 300px;
        box-shadow: 0 0 30px rgba(212, 175, 55, 0.5);
        animation: termAppear 0.5s ease-out;
    `;
    notification.innerHTML = `
        <h3 style="color: #d4af37; margin-bottom: 10px;">${term}</h3>
        <p>${description}</p>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 4000);
}

function createMagicalEffect(icon, text) {
    // 获取画布位置和尺寸
    const canvasRect = canvas.getBoundingClientRect();
    const canvasCenterX = canvasRect.left + canvasRect.width / 2;
    const canvasCenterY = canvasRect.top + canvasRect.height / 2;
    
    const effect = document.createElement('div');
    effect.style.cssText = `
        position: fixed;
        top: ${canvasCenterY}px;
        left: ${canvasCenterX}px;
        transform: translate(-50%, -50%);
        font-size: 4rem;
        z-index: 1000;
        pointer-events: none;
        animation: magicalEffect 2s ease-out forwards;
    `;
    effect.textContent = icon;
    
    const textEffect = document.createElement('div');
    textEffect.style.cssText = `
        position: fixed;
        top: ${canvasCenterY + 60}px;
        left: ${canvasCenterX}px;
        transform: translate(-50%, -50%);
        color: #d4af37;
        font-size: 1.5rem;
        font-weight: bold;
        z-index: 1000;
        pointer-events: none;
        animation: magicalTextEffect 2s ease-out forwards;
        text-shadow: 0 0 10px rgba(212, 175, 55, 0.8);
    `;
    textEffect.textContent = text;
    
    document.body.appendChild(effect);
    document.body.appendChild(textEffect);
    
    setTimeout(() => {
        effect.remove();
        textEffect.remove();
    }, 2000);
}

function displaySpellOnCanvas(spellName) {
    // 在画布中央显示咒语名称
    const fontSize = 48;
    ctx.font = `bold ${fontSize}px Arial`;
    ctx.fillStyle = '#d4af37'; // 金色
    ctx.strokeStyle = '#2c1810'; // 深棕色描边
    ctx.lineWidth = 3;
    
    // 计算文字位置（画布中央）
    const textMetrics = ctx.measureText(spellName);
    const x = (canvas.width - textMetrics.width) / 2;
    const y = canvas.height / 2;
    
    // 绘制文字描边和填充
    ctx.strokeText(spellName, x, y);
    ctx.fillText(spellName, x, y);
    
    // 2秒后清除文字
    setTimeout(() => {
        // 清除画布上的文字区域
        ctx.clearRect(x - 10, y - fontSize - 10, textMetrics.width + 20, fontSize + 20);
        // 重新绘制画布背景
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(x - 10, y - fontSize - 10, textMetrics.width + 20, fontSize + 20);
    }, 2000);
}

// 图片导入功能
function importImage() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
                const img = new Image();
                img.onload = function() {
                    // 计算图片在画布左上角的显示尺寸
                    const maxWidth = 200; // 最大宽度
                    const maxHeight = 150; // 最大高度
                    
                    let displayWidth = img.width;
                    let displayHeight = img.height;
                    
                    // 按比例缩放
                    if (displayWidth > maxWidth) {
                        const ratio = maxWidth / displayWidth;
                        displayWidth = maxWidth;
                        displayHeight = displayHeight * ratio;
                    }
                    
                    if (displayHeight > maxHeight) {
                        const ratio = maxHeight / displayHeight;
                        displayHeight = maxHeight;
                        displayWidth = displayWidth * ratio;
                    }
                    
                    // 创建图片对象，默认放在左上角
                    const imageObj = {
                        element: img,
                        x: 20, // 左边距
                        y: 20, // 上边距
                        width: displayWidth,
                        height: displayHeight,
                        originalWidth: img.width,
                        originalHeight: img.height,
                        isSelected: false,
                        isDragging: false,
                        dragStartX: 0,
                        dragStartY: 0,
                        type: 'imported', // 标记为导入图片类型
                        name: file.name
                    };
                    
                    // 添加新图片（不清除原有图片）
                    importedImages.push(imageObj);
                    selectedImageIndex = importedImages.length - 1; // 选中新导入的图片
                    
                    // 重绘画布
                    redrawCanvas();
                    
                    // 更新图片计数器
                    updateImageCounter();
                    
                    // 显示成功消息
                    showNotification(`图片已导入到左上角，点击图片进行移动，双击放大，Delete删除`);
                };
                img.src = event.target.result;
            };
            reader.readAsDataURL(file);
        }
    };
    input.click();
}

// 绘制所有导入的图片
function drawImportedImages() {
    // 重新绘制画布历史（包含所有绘图内容）
    if (canvasHistory.length > 0) {
        const img = new Image();
        img.onload = function() {
            ctx.drawImage(img, 0, 0);
            // 绘制所有导入的图片
            importedImages.forEach((img, index) => {
                ctx.drawImage(img.element, img.x, img.y, img.width, img.height);
                
                // 如果是图纸类型，添加边框
                if (img.type === 'template') {
                    ctx.strokeStyle = '#d4af37';
                    ctx.lineWidth = 3;
                    ctx.strokeRect(img.x, img.y, img.width, img.height);
                }
                
                // 为选中的图片添加高亮边框
                if (index === selectedImageIndex) {
                    ctx.strokeStyle = '#ff0000';
                    ctx.lineWidth = 2;
                    ctx.setLineDash([5, 5]);
                    ctx.strokeRect(img.x - 2, img.y - 2, img.width + 4, img.height + 4);
                    ctx.setLineDash([]);
                }
            });
        };
        img.src = canvasHistory[currentHistoryIndex];
    }
}

// 绘制图片缩放信息
function drawImageScaleInfo(img, x, y) {
    const scaleRatio = (img.width / img.originalWidth).toFixed(1);
    const scaleText = `${scaleRatio}x`;
    const deleteText = 'Delete删除';
    
    // 设置文本样式
    ctx.fillStyle = '#ff0000';
    ctx.strokeStyle = '#ffffff';
    ctx.lineWidth = 3;
    ctx.font = 'bold 14px Arial';
    ctx.textAlign = 'center';
    
    // 计算缩放信息文本位置（在图片右上角）
    const scaleTextX = x + img.width - 10;
    const scaleTextY = y + 20;
    
    // 绘制缩放信息文本背景
    ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
    const scaleTextMetrics = ctx.measureText(scaleText);
    const scaleTextWidth = scaleTextMetrics.width + 10;
    const scaleTextHeight = 20;
    ctx.fillRect(scaleTextX - scaleTextWidth/2, scaleTextY - scaleTextHeight, scaleTextWidth, scaleTextHeight);
    
    // 绘制缩放信息文本
    ctx.fillStyle = '#ffffff';
    ctx.fillText(scaleText, scaleTextX, scaleTextY);
    
    // 计算删除提示文本位置（在图片左上角）
    const deleteTextX = x + 10;
    const deleteTextY = y + 20;
    
    // 绘制删除提示文本背景
    ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
    const deleteTextMetrics = ctx.measureText(deleteText);
    const deleteTextWidth = deleteTextMetrics.width + 10;
    const deleteTextHeight = 20;
    ctx.fillRect(deleteTextX - deleteTextWidth/2, deleteTextY - deleteTextHeight, deleteTextWidth, deleteTextHeight);
    
    // 绘制删除提示文本
    ctx.fillStyle = '#ffffff';
    ctx.fillText(deleteText, deleteTextX, deleteTextY);
}

// 重绘整个画布（包括导入的图片）
function redrawCanvas() {
    // 重新绘制画布历史
    if (canvasHistory.length > 0) {
        const img = new Image();
        img.onload = function() {
            ctx.drawImage(img, 0, 0);
            // 绘制所有导入的图片
            importedImages.forEach((img, index) => {
                ctx.drawImage(img.element, img.x, img.y, img.width, img.height);
                
                // 如果是图纸类型，添加边框
                if (img.type === 'template') {
                    ctx.strokeStyle = '#d4af37';
                    ctx.lineWidth = 3;
                    ctx.strokeRect(img.x, img.y, img.width, img.height);
                }
                
                // 为选中的图片添加高亮边框和缩放信息
                if (index === selectedImageIndex) {
                    ctx.strokeStyle = '#ff0000';
                    ctx.lineWidth = 2;
                    ctx.setLineDash([5, 5]);
                    ctx.strokeRect(img.x - 2, img.y - 2, img.width + 4, img.height + 4);
                    ctx.setLineDash([]);
                    
                    // 绘制缩放信息
                    drawImageScaleInfo(img, img.x, img.y);
                }
            });
        };
        img.src = canvasHistory[currentHistoryIndex];
    } else {
        // 如果没有历史记录，绘制白色背景
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        // 绘制所有导入的图片
        importedImages.forEach((img, index) => {
            ctx.drawImage(img.element, img.x, img.y, img.width, img.height);
            
            // 如果是图纸类型，添加边框
            if (img.type === 'template') {
                ctx.strokeStyle = '#d4af37';
                ctx.lineWidth = 3;
                ctx.strokeRect(img.x, img.y, img.width, img.height);
            }
            
            // 为选中的图片添加高亮边框和缩放信息
            if (index === selectedImageIndex) {
                ctx.strokeStyle = '#ff0000';
                ctx.lineWidth = 2;
                ctx.setLineDash([5, 5]);
                ctx.strokeRect(img.x - 2, img.y - 2, img.width + 4, img.height + 4);
                ctx.setLineDash([]);
                
                // 绘制缩放信息
                drawImageScaleInfo(img, img.x, img.y);
            }
        });
    }
}

// 检查点击是否在图片上
function getImageAtPosition(x, y) {
    for (let i = importedImages.length - 1; i >= 0; i--) {
        const img = importedImages[i];
        if (x >= img.x && x <= img.x + img.width && 
            y >= img.y && y <= img.y + img.height) {
            return { image: img, index: i };
        }
    }
    return null;
}

// 处理图片的鼠标事件
function handleImageMouseDown(e) {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    const imageInfo = getImageAtPosition(x, y);
    if (imageInfo) {
        const img = imageInfo.image;
        
        // 设置当前选中的图片
        selectedImageIndex = imageInfo.index;
        
        // 开始拖拽
        img.isDragging = true;
        img.dragStartX = x - img.x;
        img.dragStartY = y - img.y;
        
        // 将图片移到最前面（Z轴顺序）
        importedImages.splice(imageInfo.index, 1);
        importedImages.push(img);
        
        // 更新选中索引（因为图片位置改变了）
        selectedImageIndex = importedImages.length - 1;
        
        // 重绘画布以显示选中状态
        redrawCanvas();
        
        e.preventDefault();
        e.stopPropagation();
    }
}

function handleImageMouseMove(e) {
    if (importedImages.some(img => img.isDragging)) {
        const rect = canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        importedImages.forEach(img => {
            if (img.isDragging) {
                img.x = x - img.dragStartX;
                img.y = y - img.dragStartY;
                
                // 限制图片不超出画布边界
                img.x = Math.max(0, Math.min(img.x, canvas.width - img.width));
                img.y = Math.max(0, Math.min(img.y, canvas.height - img.height));
                
                redrawCanvas();
            }
        });
        
        e.preventDefault();
        e.stopPropagation();
    }
}

function handleImageMouseUp(e) {
    importedImages.forEach(img => {
        img.isDragging = false;
    });
}

// 画布鼠标事件处理函数
function handleCanvasMouseDown(e) {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // 首先检查是否点击在图片上
    const imageInfo = getImageAtPosition(x, y);
    if (imageInfo) {
        handleImageMouseDown(e);
        return;
    }
    
    // 如果没有点击在图片上，则开始绘画
    startDrawing(e);
}

function handleCanvasMouseMove(e) {
    // 首先检查是否有图片正在被拖拽
    if (importedImages.some(img => img.isDragging)) {
        handleImageMouseMove(e);
        return;
    }
    
    // 如果没有图片被拖拽，则处理绘画
    draw(e);
}

function handleCanvasMouseUp(e) {
    // 处理图片拖拽结束
    handleImageMouseUp(e);
    
    // 处理绘画结束
    stopDrawing(e);
}

// 图片缩放功能
function handleImageWheel(e) {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    const imageInfo = getImageAtPosition(x, y);
    if (imageInfo && e.ctrlKey) {
        e.preventDefault();
        e.stopPropagation();
        
        const img = imageInfo.image;
        
        // 设置当前选中的图片
        selectedImageIndex = imageInfo.index;
        
        const scale = e.deltaY > 0 ? 0.9 : 1.1;
        
        img.width *= scale;
        img.height *= scale;
        
        // 限制最小和最大尺寸
        img.width = Math.max(20, Math.min(img.width, canvas.width));
        img.height = Math.max(20, Math.min(img.height, canvas.height));
        
        redrawCanvas();
    }
}

// 倒计时功能
function initializeCountdown() {
    // 设置目标日期（每年9月1日，霍格沃茨开学日）
    const now = new Date();
    const currentYear = now.getFullYear();
    const targetDate = new Date(currentYear, 8, 1); // 9月1日（月份从0开始）
    
    // 如果今年的开学日已经过了，设置为明年的开学日
    if (now > targetDate) {
        targetDate.setFullYear(currentYear + 1);
    }
    
    function updateCountdown() {
        const now = new Date();
        const timeDifference = targetDate - now;
        
        if (timeDifference > 0) {
            const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
            const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
            
            document.getElementById('days').textContent = days.toString().padStart(2, '0');
            document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
            document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
            document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');
        } else {
            // 如果倒计时结束，重新设置为明年的开学日
            targetDate.setFullYear(targetDate.getFullYear() + 1);
        }
    }
    
    // 立即更新一次
    updateCountdown();
    
    // 每秒更新一次
    setInterval(updateCountdown, 1000);
}

// 背景轮播功能
function initializeBackgroundSlideshow() {
    const backgroundImages = [
        '图纸/封面壁纸1.jpg',
        '图纸/封面壁纸2.jpg',
        '图纸/封面壁纸3.jpg',
        '图纸/封面壁纸4.jpg',
        '图纸/封面壁纸5.jpg',
        '图纸/封面壁纸6.jpg'
    ];
    
    let currentImageIndex = 0;
    let interval;
    const welcomePage = document.getElementById('welcomePage');
    
    if (welcomePage) {
        // 切换背景图片的函数
        function changeBackgroundImage(index) {
            const nextImage = backgroundImages[index];
            
            // 预加载下一张图片
            const img = new Image();
            img.onload = function() {
                welcomePage.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.5)), url('${nextImage}')`;
            };
            img.src = nextImage;
        }
        
        // 启动自动播放
        function startAutoPlay() {
            interval = setInterval(() => {
                currentImageIndex = (currentImageIndex + 1) % backgroundImages.length;
                changeBackgroundImage(currentImageIndex);
            }, 3000);
        }
        
        // 停止自动播放
        function stopAutoPlay() {
            if (interval) {
                clearInterval(interval);
            }
        }
        
        // 开始自动播放
        startAutoPlay();
        
        // 添加鼠标滚轮控制
        welcomePage.addEventListener('wheel', function(e) {
            e.preventDefault();
            
            // 停止自动播放
            stopAutoPlay();
            
            if (e.deltaY > 0) {
                // 向下滚动，切换到下一张
                currentImageIndex = (currentImageIndex + 1) % backgroundImages.length;
            } else {
                // 向上滚动，切换到上一张
                currentImageIndex = (currentImageIndex - 1 + backgroundImages.length) % backgroundImages.length;
            }
            
            changeBackgroundImage(currentImageIndex);
            
            // 3秒后重新启动自动播放
            setTimeout(() => {
                startAutoPlay();
            }, 3000);
        });
    }
}

// 烟花特效功能
function initializeFireworks() {
    const welcomePage = document.getElementById('welcomePage');
    if (welcomePage) {
        welcomePage.addEventListener('click', createFirework);
    }
}

function createFirework(e) {
    const fireworksContainer = document.getElementById('fireworksContainer');
    if (!fireworksContainer) return;
    
    const rect = fireworksContainer.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // 创建烟花爆炸效果
    const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ffa500', '#ff69b4'];
    const particleCount = 20;
    
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'firework-particle';
        
        // 随机颜色
        const color = colors[Math.floor(Math.random() * colors.length)];
        particle.style.backgroundColor = color;
        particle.style.boxShadow = `0 0 6px ${color}`;
        
        // 随机方向
        const angle = (Math.PI * 2 * i) / particleCount;
        const distance = 50 + Math.random() * 100;
        const dx = Math.cos(angle) * distance;
        const dy = Math.sin(angle) * distance;
        
        particle.style.left = x + 'px';
        particle.style.top = y + 'px';
        particle.style.setProperty('--dx', dx + 'px');
        particle.style.setProperty('--dy', dy + 'px');
        
        fireworksContainer.appendChild(particle);
        
        // 动画结束后移除粒子
        setTimeout(() => {
            if (particle.parentNode) {
                particle.parentNode.removeChild(particle);
            }
        }, 1500);
    }
}

// 分院测试功能
function initializeSortingTest() {
    // 绑定分院按钮事件
    document.getElementById('sortingButton').addEventListener('click', showSortingPage);
    document.getElementById('startSortingBtn').addEventListener('click', startSortingTest);
    document.getElementById('backToWelcomeBtn').addEventListener('click', backToWelcome);
}

// 分院测试数据
const sortingQuestions = [
    {
        question: "你更喜欢哪种魔法？",
        options: [
            { text: "勇敢无畏的进攻魔法", house: "gryffindor" },
            { text: "智慧深奥的学术魔法", house: "ravenclaw" },
            { text: "实用有效的防御魔法", house: "hufflepuff" },
            { text: "强大神秘的黑暗魔法", house: "slytherin" }
        ]
    },
    {
        question: "在危险时刻，你会怎么做？",
        options: [
            { text: "勇敢地面对挑战", house: "gryffindor" },
            { text: "冷静分析情况", house: "ravenclaw" },
            { text: "保护朋友的安全", house: "hufflepuff" },
            { text: "寻找最有利的解决方案", house: "slytherin" }
        ]
    },
    {
        question: "你最喜欢的学习方式是什么？",
        options: [
            { text: "实践和冒险", house: "gryffindor" },
            { text: "研究和探索", house: "ravenclaw" },
            { text: "合作和分享", house: "hufflepuff" },
            { text: "竞争和超越", house: "slytherin" }
        ]
    },
    {
        question: "你更看重哪种品质？",
        options: [
            { text: "勇气和正义", house: "gryffindor" },
            { text: "智慧和创造力", house: "ravenclaw" },
            { text: "忠诚和善良", house: "hufflepuff" },
            { text: "野心和决心", house: "slytherin" }
        ]
    },
    {
        question: "你希望别人如何评价你？",
        options: [
            { text: "勇敢无畏的英雄", house: "gryffindor" },
            { text: "聪明睿智的学者", house: "ravenclaw" },
            { text: "可靠忠诚的朋友", house: "hufflepuff" },
            { text: "成功强大的领袖", house: "slytherin" }
        ]
    }
];

const houseData = {
    gryffindor: {
        name: "格兰芬多",
        crest: "🦁",
        description: "格兰芬多学院以勇敢、无畏、骑士精神和冒险精神而闻名。学院创始人戈德里克·格兰芬多认为，最勇敢的学生应该被分到他的学院。",
        traits: ["勇敢无畏", "骑士精神", "冒险精神", "正义感强", "保护弱者", "热情开朗"]
    },
    ravenclaw: {
        name: "拉文克劳",
        crest: "🦅",
        description: "拉文克劳学院以智慧、创造力、学术成就和独立思考而闻名。学院创始人罗伊纳·拉文克劳认为，最聪明的学生应该被分到她的学院。",
        traits: ["智慧聪慧", "创造力强", "学术成就", "独立思考", "好奇心强", "追求知识"]
    },
    hufflepuff: {
        name: "赫奇帕奇",
        crest: "🦡",
        description: "赫奇帕奇学院以忠诚、善良、耐心和勤奋而闻名。学院创始人赫尔加·赫奇帕奇认为，所有学生都应该被平等对待。",
        traits: ["忠诚可靠", "善良友好", "耐心勤奋", "公平正义", "包容开放", "团队合作"]
    },
    slytherin: {
        name: "斯莱特林",
        crest: "🐍",
        description: "斯莱特林学院以野心、精明、领导力和决心而闻名。学院创始人萨拉查·斯莱特林认为，最纯血统的学生应该被分到他的学院。",
        traits: ["野心勃勃", "精明能干", "领导才能", "意志坚定", "追求成功", "家族荣誉"]
    }
};

let currentQuestionIndex = 0;
let houseScores = {
    gryffindor: 0,
    ravenclaw: 0,
    hufflepuff: 0,
    slytherin: 0
};

// 魔杖测试相关变量
let currentWandQuestionIndex = 0;
let wandPreferences = {
    wood: [],
    core: [],
    length: [],
    flexibility: []
};

// 魔杖测试问题
const wandQuestions = [
    {
        question: "你更喜欢哪种木材的特性？",
        options: [
            { text: "坚韧耐用", wood: "oak", core: "dragon", length: "long", flexibility: "rigid" },
            { text: "灵活优雅", wood: "willow", core: "unicorn", length: "medium", flexibility: "springy" },
            { text: "神秘强大", wood: "hawthorn", core: "phoenix", length: "long", flexibility: "slightly-springy" },
            { text: "温暖亲和", wood: "cherry", core: "unicorn", length: "medium", flexibility: "supple" }
        ]
    },
    {
        question: "你更倾向于哪种魔法风格？",
        options: [
            { text: "直接有力", wood: "oak", core: "dragon", length: "long", flexibility: "rigid" },
            { text: "温和治愈", wood: "willow", core: "unicorn", length: "medium", flexibility: "springy" },
            { text: "复杂多变", wood: "hawthorn", core: "phoenix", length: "long", flexibility: "slightly-springy" },
            { text: "平衡和谐", wood: "cherry", core: "unicorn", length: "medium", flexibility: "supple" }
        ]
    },
    {
        question: "你如何处理冲突？",
        options: [
            { text: "正面应对", wood: "oak", core: "dragon", length: "long", flexibility: "rigid" },
            { text: "寻求和解", wood: "willow", core: "unicorn", length: "medium", flexibility: "springy" },
            { text: "智取巧胜", wood: "hawthorn", core: "phoenix", length: "long", flexibility: "slightly-springy" },
            { text: "保持中立", wood: "cherry", core: "unicorn", length: "medium", flexibility: "supple" }
        ]
    },
    {
        question: "你更喜欢哪种学习环境？",
        options: [
            { text: "挑战性的", wood: "oak", core: "dragon", length: "long", flexibility: "rigid" },
            { text: "支持性的", wood: "willow", core: "unicorn", length: "medium", flexibility: "springy" },
            { text: "探索性的", wood: "hawthorn", core: "phoenix", length: "long", flexibility: "slightly-springy" },
            { text: "平衡的", wood: "cherry", core: "unicorn", length: "medium", flexibility: "supple" }
        ]
    },
    {
        question: "你如何看待传统与创新？",
        options: [
            { text: "重视传统", wood: "oak", core: "dragon", length: "long", flexibility: "rigid" },
            { text: "温和改良", wood: "willow", core: "unicorn", length: "medium", flexibility: "springy" },
            { text: "大胆创新", wood: "hawthorn", core: "phoenix", length: "long", flexibility: "slightly-springy" },
            { text: "平衡发展", wood: "cherry", core: "unicorn", length: "medium", flexibility: "supple" }
        ]
    }
];

// 魔杖数据
const wandData = {
    oak: {
        name: "橡木魔杖",
        wood: "橡木",
        core: "龙心弦",
        length: "14英寸",
        flexibility: "坚硬",
        description: "橡木魔杖象征着力量、勇气和坚韧。它适合那些有强烈意志力和决心的巫师。",
        traits: ["力量", "勇气", "坚韧", "意志力", "决心", "领导力"]
    },
    willow: {
        name: "柳木魔杖",
        wood: "柳木",
        core: "独角兽毛",
        length: "12¾英寸",
        flexibility: "弹性",
        description: "柳木魔杖代表着治愈、智慧和直觉。它适合那些有同情心和治愈天赋的巫师。",
        traits: ["治愈", "智慧", "直觉", "同情心", "温和", "平衡"]
    },
    hawthorn: {
        name: "山楂木魔杖",
        wood: "山楂木",
        core: "凤凰羽毛",
        length: "11¾英寸",
        flexibility: "稍具弹性",
        description: "山楂木魔杖充满矛盾，既能治愈也能诅咒。它适合那些经历内心冲突或动荡时期的巫师。",
        traits: ["矛盾性", "复杂性", "治愈能力", "诅咒能力", "适应性", "神秘性"]
    },
    cherry: {
        name: "樱桃木魔杖",
        wood: "樱桃木",
        core: "独角兽毛",
        length: "13英寸",
        flexibility: "柔韧",
        description: "樱桃木魔杖代表着优雅、和谐和创造力。它适合那些有艺术天赋和追求完美的巫师。",
        traits: ["优雅", "和谐", "创造力", "艺术天赋", "完美主义", "亲和力"]
    }
};

function showSortingPage() {
    document.getElementById('welcomePage').classList.add('hidden');
    document.getElementById('sortingPage').classList.remove('hidden');
}

function backToWelcome() {
    document.getElementById('sortingPage').classList.add('hidden');
    document.getElementById('welcomePage').classList.remove('hidden');
    resetSortingTest();
}

function startSortingTest() {
    currentQuestionIndex = 0;
    houseScores = { gryffindor: 0, ravenclaw: 0, hufflepuff: 0, slytherin: 0 };
    
    document.getElementById('startSortingBtn').style.display = 'none';
    document.getElementById('sortingQuestions').style.display = 'block';
    document.getElementById('sortingResult').style.display = 'none';
    
    showQuestion();
}

function showQuestion() {
    if (currentQuestionIndex >= sortingQuestions.length) {
        showResult();
        return;
    }
    
    const question = sortingQuestions[currentQuestionIndex];
    document.getElementById('questionText').textContent = question.question;
    
    const answerOptions = document.getElementById('answerOptions');
    answerOptions.innerHTML = '';
    
    question.options.forEach((option, index) => {
        const optionElement = document.createElement('div');
        optionElement.className = 'answer-option';
        optionElement.textContent = option.text;
        optionElement.addEventListener('click', () => selectAnswer(option.house));
        answerOptions.appendChild(optionElement);
    });
}

function selectAnswer(house) {
    houseScores[house]++;
    currentQuestionIndex++;
    
    if (currentQuestionIndex < sortingQuestions.length) {
        showQuestion();
    } else {
        showResult();
    }
}

function showResult() {
    // 计算最高分的学院
    let maxScore = 0;
    let selectedHouse = 'gryffindor';
    
    for (const [house, score] of Object.entries(houseScores)) {
        if (score > maxScore) {
            maxScore = score;
            selectedHouse = house;
        }
    }
    
    const house = houseData[selectedHouse];
    
    document.getElementById('houseName').textContent = house.name;
    document.getElementById('houseCrest').textContent = house.crest;
    document.getElementById('houseDescription').textContent = house.description;
    
    const traitsList = document.getElementById('houseTraits');
    traitsList.innerHTML = '';
    house.traits.forEach(trait => {
        const li = document.createElement('li');
        li.textContent = trait;
        traitsList.appendChild(li);
    });
    
    document.getElementById('sortingQuestions').style.display = 'none';
    document.getElementById('sortingResult').style.display = 'block';
    document.getElementById('startSortingBtn').style.display = 'inline-block';
    document.getElementById('startSortingBtn').textContent = '重新测试';
}

function resetSortingTest() {
    currentQuestionIndex = 0;
    houseScores = { gryffindor: 0, ravenclaw: 0, hufflepuff: 0, slytherin: 0 };
    
    document.getElementById('sortingQuestions').style.display = 'none';
    document.getElementById('sortingResult').style.display = 'none';
    document.getElementById('startSortingBtn').style.display = 'inline-block';
    document.getElementById('startSortingBtn').textContent = '开始分院';
}

// 魔杖测试功能
function initializeWandTest() {
    document.getElementById('wandButton').addEventListener('click', showWandPage);
    document.getElementById('startWandBtn').addEventListener('click', startWandTest);
    document.getElementById('backToWelcomeFromWandBtn').addEventListener('click', backToWelcomeFromWand);
}

function showWandPage() {
    document.getElementById('welcomePage').classList.add('hidden');
    document.getElementById('wandPage').classList.remove('hidden');
}

function backToWelcomeFromWand() {
    document.getElementById('wandPage').classList.add('hidden');
    document.getElementById('welcomePage').classList.remove('hidden');
    resetWandTest();
}

function startWandTest() {
    currentWandQuestionIndex = 0;
    wandPreferences = { wood: [], core: [], length: [], flexibility: [] };
    
    document.getElementById('startWandBtn').style.display = 'none';
    document.getElementById('wandQuestions').style.display = 'block';
    document.getElementById('wandResult').style.display = 'none';
    
    showWandQuestion();
}

function showWandQuestion() {
    if (currentWandQuestionIndex >= wandQuestions.length) {
        showWandResult();
        return;
    }
    
    const question = wandQuestions[currentWandQuestionIndex];
    document.getElementById('wandQuestionText').textContent = question.question;
    
    const answerOptions = document.getElementById('wandAnswerOptions');
    answerOptions.innerHTML = '';
    
    question.options.forEach((option, index) => {
        const optionElement = document.createElement('div');
        optionElement.className = 'answer-option';
        optionElement.textContent = option.text;
        optionElement.addEventListener('click', () => selectWandAnswer(option));
        answerOptions.appendChild(optionElement);
    });
}

function selectWandAnswer(option) {
    wandPreferences.wood.push(option.wood);
    wandPreferences.core.push(option.core);
    wandPreferences.length.push(option.length);
    wandPreferences.flexibility.push(option.flexibility);
    
    currentWandQuestionIndex++;
    
    if (currentWandQuestionIndex < wandQuestions.length) {
        showWandQuestion();
    } else {
        showWandResult();
    }
}

function showWandResult() {
    // 计算最常选择的魔杖类型
    const woodCount = {};
    wandPreferences.wood.forEach(wood => {
        woodCount[wood] = (woodCount[wood] || 0) + 1;
    });
    
    let selectedWood = 'oak';
    let maxCount = 0;
    
    for (const [wood, count] of Object.entries(woodCount)) {
        if (count > maxCount) {
            maxCount = count;
            selectedWood = wood;
        }
    }
    
    const wand = wandData[selectedWood];
    
    document.getElementById('wandName').textContent = wand.name;
    document.getElementById('wandWood').textContent = `木材：${wand.wood}`;
    document.getElementById('wandCore').textContent = `杖芯：${wand.core}`;
    document.getElementById('wandLength').textContent = `长度：${wand.length}`;
    document.getElementById('wandFlexibility').textContent = `弹性：${wand.flexibility}`;
    document.getElementById('wandDescription').textContent = wand.description;
    
    const traitsList = document.getElementById('wandTraits');
    traitsList.innerHTML = '';
    wand.traits.forEach(trait => {
        const li = document.createElement('li');
        li.textContent = trait;
        traitsList.appendChild(li);
    });
    
    document.getElementById('wandQuestions').style.display = 'none';
    document.getElementById('wandResult').style.display = 'block';
    document.getElementById('startWandBtn').style.display = 'inline-block';
    document.getElementById('startWandBtn').textContent = '重新测试';
}

function resetWandTest() {
    currentWandQuestionIndex = 0;
    wandPreferences = { wood: [], core: [], length: [], flexibility: [] };
    document.getElementById('startWandBtn').textContent = '开始测试';
    document.getElementById('wandQuestions').style.display = 'none';
    document.getElementById('wandResult').style.display = 'none';
    document.getElementById('wandMessage').textContent = '点击开始测试，奥利凡德将为你选择最适合的魔杖...';
}

// 全局函数
window.closeSpellsModal = closeSpellsModal;
window.closeTemplatesModal = closeTemplatesModal;
window.showSpellInfo = showSpellInfo;
window.toggleCategory = toggleCategory;
window.loadTemplate = loadTemplate;
window.closeSettings = closeSettings;
window.saveSettings = saveSettings;
window.resetSettings = resetSettings;

// 通知函数
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    
    // 根据类型设置不同的样式
    let background, color, icon;
    switch(type) {
        case 'success':
            background = 'linear-gradient(45deg, #4CAF50, #45a049)';
            color = '#ffffff';
            icon = '✅';
            break;
        case 'error':
            background = 'linear-gradient(45deg, #f44336, #d32f2f)';
            color = '#ffffff';
            icon = '❌';
            break;
        case 'warning':
            background = 'linear-gradient(45deg, #ff9800, #f57c00)';
            color = '#ffffff';
            icon = '⚠️';
            break;
        case 'info':
        default:
            background = 'linear-gradient(45deg, #d4af37, #ffd700)';
            color = '#2c1810';
            icon = '💫';
            break;
    }
    
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${background};
        color: ${color};
        padding: 15px 25px;
        border-radius: 10px;
        font-weight: bold;
        z-index: 1001;
        animation: slideIn 0.5s ease-out;
        box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        display: flex;
        align-items: center;
        gap: 8px;
    `;
    notification.innerHTML = `<span>${icon}</span><span>${message}</span>`;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes magicalEffect {
        0% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.5);
        }
        50% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1.2);
        }
        100% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(1.5);
        }
    }
    
    @keyframes magicalTextEffect {
        0% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.8);
        }
        50% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1.1);
        }
        100% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(1.3);
        }
    }
    
    @keyframes termAppear {
        from {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.5);
        }
        to {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
    }
`;
document.head.appendChild(style);

// 颜色主题相关函数
function toggleColorDropdown() {
    const dropdown = document.getElementById('colorDropdownContent');
    dropdown.classList.toggle('show');
}

function selectColorTheme(e) {
    const theme = e.target.dataset.theme;
    const themeData = colorThemes[theme];
    
    if (themeData) {
        // 更新按钮文本
        const btn = document.getElementById('colorDropdownBtn');
        btn.textContent = `🎨 ${themeData.name}`;
        
        // 更新选中状态
        document.querySelectorAll('.color-theme-option').forEach(option => {
            option.classList.remove('active');
        });
        e.target.classList.add('active');
        
        // 生成颜色按钮
        generateColorButtons(themeData.colors);
        
        // 关闭下拉菜单
        document.getElementById('colorDropdownContent').classList.remove('show');
        
        showNotification(`已切换到${themeData.name}色系`);
    }
}

function generateColorButtons(colors) {
    const quickColorsContainer = document.getElementById('quickColors');
    quickColorsContainer.innerHTML = '';
    
    colors.forEach(color => {
        const colorBtn = document.createElement('div');
        colorBtn.className = 'color-btn';
        colorBtn.style.background = color;
        colorBtn.dataset.color = color;
        colorBtn.title = color;
        
        colorBtn.addEventListener('click', function() {
            currentColor = color;
            document.getElementById('colorPicker').value = color;
            if (!isEraser) {
                ctx.strokeStyle = color;
            }
            showNotification(`已选择颜色: ${color}`);
        });
        
        quickColorsContainer.appendChild(colorBtn);
    });
}

// 初始化默认颜色主题
function initializeColorTheme() {
    // 默认选择莫兰迪主题
    const defaultTheme = colorThemes.morandi;
    generateColorButtons(defaultTheme.colors);
    
    // 设置默认选中状态
    document.querySelector('[data-theme="morandi"]').classList.add('active');
    document.getElementById('colorDropdownBtn').textContent = `🎨 ${defaultTheme.name}`;
    
    // 初始化自定义颜色预览
    updateColorPreview(currentColor);
    
    // 绑定颜色选择器事件
    document.getElementById('colorPicker').addEventListener('change', function(e) {
        const color = e.target.value;
        currentColor = color;
        updateColorPreview(color);
        
        // 同步更新RGB输入框
        const rgb = hexToRgb(color);
        if (rgb) {
            document.getElementById('rgbR').value = rgb.r;
            document.getElementById('rgbG').value = rgb.g;
            document.getElementById('rgbB').value = rgb.b;
        }
        
        if (!isEraser) {
            ctx.strokeStyle = color;
        }
        showNotification(`已选择自定义颜色: ${color}`);
    });
}

// 切换颜色圆盘显示
function toggleColorWheel() {
    const container = document.getElementById('colorWheelContainer');
    container.classList.toggle('show');
}

// 更新颜色预览
function updateColorPreview(color) {
    const preview = document.getElementById('colorPreview');
    preview.style.background = color;
}

// 圆盘颜色选择功能
function initializeColorWheel() {
    const colorWheel = document.getElementById('colorWheel');
    
    colorWheel.addEventListener('click', function(e) {
        const rect = colorWheel.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;
        
        const deltaX = e.clientX - centerX;
        const deltaY = e.clientY - centerY;
        
        // 计算角度
        const angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
        const normalizedAngle = (angle + 360) % 360;
        
        // 根据角度选择颜色
        const hue = normalizedAngle;
        const saturation = 100;
        const lightness = 50;
        
        const color = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
        currentColor = color;
        updateColorPreview(color);
        document.getElementById('colorPicker').value = color;
        
        // 同步更新RGB输入框
        const rgb = hexToRgb(color);
        if (rgb) {
            document.getElementById('rgbR').value = rgb.r;
            document.getElementById('rgbG').value = rgb.g;
            document.getElementById('rgbB').value = rgb.b;
        }
        
        if (!isEraser) {
            ctx.strokeStyle = color;
        }
        
        showNotification(`已选择颜色: ${color}`);
    });
}

// RGB颜色相关函数
function applyRgbColor() {
    const r = parseInt(document.getElementById('rgbR').value) || 0;
    const g = parseInt(document.getElementById('rgbG').value) || 0;
    const b = parseInt(document.getElementById('rgbB').value) || 0;
    
    // 验证RGB值范围
    const validR = Math.max(0, Math.min(255, r));
    const validG = Math.max(0, Math.min(255, g));
    const validB = Math.max(0, Math.min(255, b));
    
    // 转换为十六进制颜色
    const hexColor = rgbToHex(validR, validG, validB);
    
    // 更新当前颜色
    currentColor = hexColor;
    updateColorPreview(hexColor);
    document.getElementById('colorPicker').value = hexColor;
    
    if (!isEraser) {
        ctx.strokeStyle = hexColor;
    }
    
    showNotification(`已应用RGB颜色: (${validR}, ${validG}, ${validB})`);
}

function updateRgbPreview() {
    const r = parseInt(document.getElementById('rgbR').value) || 0;
    const g = parseInt(document.getElementById('rgbG').value) || 0;
    const b = parseInt(document.getElementById('rgbB').value) || 0;
    
    const validR = Math.max(0, Math.min(255, r));
    const validG = Math.max(0, Math.min(255, g));
    const validB = Math.max(0, Math.min(255, b));
    
    const hexColor = rgbToHex(validR, validG, validB);
    
    // 更新RGB输入框的值
    document.getElementById('rgbR').value = validR;
    document.getElementById('rgbG').value = validG;
    document.getElementById('rgbB').value = validB;
    
    // 更新颜色预览
    updateColorPreview(hexColor);
}

function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

function hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

// 音频功能相关变量
let backgroundAudio = null;
let isAudioPlaying = false;

// 音频功能函数
function initializeAudio() {
    // 创建音频元素
    backgroundAudio = new Audio('海德薇变奏曲 [安眠的钢琴曲]_爱给网_aigei_com.mp3');
    backgroundAudio.loop = true;
    backgroundAudio.volume = 0.5;
    
    // 绑定音频控制事件
    document.getElementById('audioToggleBtn').addEventListener('click', toggleAudio);
    document.getElementById('audioVolumeSlider').addEventListener('input', updateAudioVolume);
    
    // 音频播放状态监听
    backgroundAudio.addEventListener('play', function() {
        isAudioPlaying = true;
        updateAudioUI();
    });
    
    backgroundAudio.addEventListener('pause', function() {
        isAudioPlaying = false;
        updateAudioUI();
    });
}

function toggleAudioPanel() {
    const panel = document.getElementById('audioControlPanel');
    panel.classList.toggle('show');
}

function toggleAudio() {
    if (isAudioPlaying) {
        backgroundAudio.pause();
    } else {
        backgroundAudio.play().catch(e => {
            console.log('音频播放失败:', e);
            showNotification('音频播放失败，请检查音频文件');
        });
    }
}

function updateAudioVolume() {
    const volume = document.getElementById('audioVolumeSlider').value;
    backgroundAudio.volume = volume;
    document.getElementById('audioVolumeValue').textContent = Math.round(volume * 100) + '%';
}

function updateAudioUI() {
    const audioBtn = document.getElementById('audioBtn');
    const toggleBtn = document.getElementById('audioToggleBtn');
    
    if (isAudioPlaying) {
        audioBtn.classList.add('playing');
        toggleBtn.textContent = '暂停音乐';
        toggleBtn.classList.add('playing');
    } else {
        audioBtn.classList.remove('playing');
        toggleBtn.textContent = '播放音乐';
        toggleBtn.classList.remove('playing');
    }
}

// 帮助功能
function showHelpModal() {
    const helpModal = document.getElementById('helpModal');
    helpModal.style.display = 'flex';
}

function closeHelpModal() {
    const helpModal = document.getElementById('helpModal');
    helpModal.style.display = 'none';
}

// 形状预览函数（拖动时实时显示）
function previewShape(endX, endY) {
    // 清除之前的预览
    redrawCanvas();
    
    // 设置绘制样式
    ctx.strokeStyle = currentColor;
    ctx.fillStyle = currentColor;
    ctx.lineWidth = currentSize;
    
    let width = endX - shapeStartX;
    let height = endY - shapeStartY;
    
    // 检查是否按住Shift键（系统画图风格的约束）
    // 使用全局变量isShiftPressed
    
    switch (currentShape) {
        case 'rectangle':
            if (isShiftPressed) {
                // 按住Shift键绘制正方形
                const size = Math.min(Math.abs(width), Math.abs(height));
                width = width >= 0 ? size : -size;
                height = height >= 0 ? size : -size;
            }
            ctx.strokeRect(shapeStartX, shapeStartY, width, height);
            break;
        case 'circle':
            if (isShiftPressed) {
                // 按住Shift键绘制正圆形
                const size = Math.min(Math.abs(width), Math.abs(height));
                width = width >= 0 ? size : -size;
                height = height >= 0 ? size : -size;
            }
            const radius = Math.sqrt(width * width + height * height);
            ctx.beginPath();
            ctx.arc(shapeStartX, shapeStartY, radius, 0, 2 * Math.PI);
            ctx.stroke();
            break;
        case 'triangle':
            ctx.beginPath();
            ctx.moveTo(shapeStartX, endY);
            ctx.lineTo(endX, endY);
            ctx.lineTo((shapeStartX + endX) / 2, shapeStartY);
            ctx.closePath();
            ctx.stroke();
            break;
        case 'line':
            if (isShiftPressed) {
                // 按住Shift键绘制水平、垂直或45度线
                const angle = Math.atan2(height, width) * 180 / Math.PI;
                if (Math.abs(angle) < 22.5) {
                    // 水平线
                    height = 0;
                } else if (Math.abs(angle - 90) < 22.5 || Math.abs(angle + 90) < 22.5) {
                    // 垂直线
                    width = 0;
                } else if (Math.abs(angle - 45) < 22.5) {
                    // 45度线
                    const size = Math.min(Math.abs(width), Math.abs(height));
                    width = width >= 0 ? size : -size;
                    height = height >= 0 ? size : -size;
                } else if (Math.abs(angle + 45) < 22.5) {
                    // -45度线
                    const size = Math.min(Math.abs(width), Math.abs(height));
                    width = width >= 0 ? size : -size;
                    height = height >= 0 ? -size : size;
                }
            }
            ctx.beginPath();
            ctx.moveTo(shapeStartX, shapeStartY);
            ctx.lineTo(shapeStartX + width, shapeStartY + height);
            ctx.stroke();
            break;
        case 'arrow':
            drawArrow(shapeStartX, shapeStartY, endX, endY);
            break;
        case 'star':
            const starSize = Math.sqrt(width * width + height * height);
            drawStar(shapeStartX, shapeStartY, starSize);
            break;
        case 'heart':
            drawHeart(shapeStartX, shapeStartY, Math.abs(width), Math.abs(height));
            break;
        case 'diamond':
            if (isShiftPressed) {
                // 按住Shift键绘制正菱形
                const size = Math.min(Math.abs(width), Math.abs(height));
                width = width >= 0 ? size : -size;
                height = height >= 0 ? size : -size;
            }
            ctx.beginPath();
            ctx.moveTo(shapeStartX, (shapeStartY + (shapeStartY + height)) / 2);
            ctx.lineTo((shapeStartX + (shapeStartX + width)) / 2, shapeStartY);
            ctx.lineTo(shapeStartX + width, (shapeStartY + (shapeStartY + height)) / 2);
            ctx.lineTo((shapeStartX + (shapeStartX + width)) / 2, shapeStartY + height);
            ctx.closePath();
            ctx.stroke();
            break;
    }
}

// 形状绘制函数（最终绘制）
function drawShape(endX, endY) {
    // 设置绘制样式
    ctx.strokeStyle = currentColor;
    ctx.fillStyle = currentColor;
    ctx.lineWidth = currentSize;
    
    let width = endX - shapeStartX;
    let height = endY - shapeStartY;
    
    // 检查是否按住Shift键（系统画图风格的约束）
    // 使用全局变量isShiftPressed
    
    switch (currentShape) {
        case 'rectangle':
            if (isShiftPressed) {
                // 按住Shift键绘制正方形
                const size = Math.min(Math.abs(width), Math.abs(height));
                width = width >= 0 ? size : -size;
                height = height >= 0 ? size : -size;
            }
            ctx.strokeRect(shapeStartX, shapeStartY, width, height);
            break;
        case 'circle':
            if (isShiftPressed) {
                // 按住Shift键绘制正圆形
                const size = Math.min(Math.abs(width), Math.abs(height));
                width = width >= 0 ? size : -size;
                height = height >= 0 ? size : -size;
            }
            const radius = Math.sqrt(width * width + height * height);
            ctx.beginPath();
            ctx.arc(shapeStartX, shapeStartY, radius, 0, 2 * Math.PI);
            ctx.stroke();
            break;
        case 'triangle':
            ctx.beginPath();
            ctx.moveTo(shapeStartX, shapeStartY + height);
            ctx.lineTo(shapeStartX + width, shapeStartY + height);
            ctx.lineTo((shapeStartX + (shapeStartX + width)) / 2, shapeStartY);
            ctx.closePath();
            ctx.stroke();
            break;
        case 'line':
            if (isShiftPressed) {
                // 按住Shift键绘制水平、垂直或45度线
                const angle = Math.atan2(height, width) * 180 / Math.PI;
                if (Math.abs(angle) < 22.5) {
                    // 水平线
                    height = 0;
                } else if (Math.abs(angle - 90) < 22.5 || Math.abs(angle + 90) < 22.5) {
                    // 垂直线
                    width = 0;
                } else if (Math.abs(angle - 45) < 22.5) {
                    // 45度线
                    const size = Math.min(Math.abs(width), Math.abs(height));
                    width = width >= 0 ? size : -size;
                    height = height >= 0 ? size : -size;
                } else if (Math.abs(angle + 45) < 22.5) {
                    // -45度线
                    const size = Math.min(Math.abs(width), Math.abs(height));
                    width = width >= 0 ? size : -size;
                    height = height >= 0 ? -size : size;
                }
            }
            ctx.beginPath();
            ctx.moveTo(shapeStartX, shapeStartY);
            ctx.lineTo(shapeStartX + width, shapeStartY + height);
            ctx.stroke();
            break;
        case 'arrow':
            drawArrow(shapeStartX, shapeStartY, shapeStartX + width, shapeStartY + height);
            break;
        case 'star':
            const starSize = Math.sqrt(width * width + height * height);
            drawStar(shapeStartX, shapeStartY, starSize);
            break;
        case 'heart':
            drawHeart(shapeStartX, shapeStartY, Math.abs(width), Math.abs(height));
            break;
        case 'diamond':
            if (isShiftPressed) {
                // 按住Shift键绘制正菱形
                const size = Math.min(Math.abs(width), Math.abs(height));
                width = width >= 0 ? size : -size;
                height = height >= 0 ? size : -size;
            }
            ctx.beginPath();
            ctx.moveTo(shapeStartX, (shapeStartY + (shapeStartY + height)) / 2);
            ctx.lineTo((shapeStartX + (shapeStartX + width)) / 2, shapeStartY);
            ctx.lineTo(shapeStartX + width, (shapeStartY + (shapeStartY + height)) / 2);
            ctx.lineTo((shapeStartX + (shapeStartX + width)) / 2, shapeStartY + height);
            ctx.closePath();
            ctx.stroke();
            break;
    }
}

function drawArrow(startX, startY, endX, endY) {
    const headLength = 15;
    const angle = Math.atan2(endY - startY, endX - startX);
    
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.lineTo(endX - headLength * Math.cos(angle - Math.PI / 6), endY - headLength * Math.sin(angle - Math.PI / 6));
    ctx.moveTo(endX, endY);
    ctx.lineTo(endX - headLength * Math.cos(angle + Math.PI / 6), endY - headLength * Math.sin(angle + Math.PI / 6));
    ctx.stroke();
}

function drawStar(centerX, centerY, radius) {
    const spikes = 5;
    const outerRadius = radius;
    const innerRadius = radius * 0.4;
    
    ctx.beginPath();
    for (let i = 0; i < spikes * 2; i++) {
        const angle = (i * Math.PI) / spikes;
        const r = i % 2 === 0 ? outerRadius : innerRadius;
        const x = centerX + Math.cos(angle) * r;
        const y = centerY + Math.sin(angle) * r;
        
        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }
    ctx.closePath();
    ctx.stroke();
}

function drawHeart(centerX, centerY, width, height) {
    const scale = Math.min(width, height) / 50;
    
    ctx.beginPath();
    ctx.moveTo(centerX, centerY + 5 * scale);
    ctx.bezierCurveTo(
        centerX, centerY, 
        centerX - 6 * scale, centerY, 
        centerX - 6 * scale, centerY + 7 * scale
    );
    ctx.bezierCurveTo(
        centerX - 6 * scale, centerY + 11 * scale, 
        centerX - 3 * scale, centerY + 15 * scale, 
        centerX, centerY + 17 * scale
    );
    ctx.bezierCurveTo(
        centerX + 3 * scale, centerY + 15 * scale, 
        centerX + 6 * scale, centerY + 11 * scale, 
        centerX + 6 * scale, centerY + 7 * scale
    );
    ctx.bezierCurveTo(
        centerX + 6 * scale, centerY, 
        centerX, centerY, 
        centerX, centerY + 5 * scale
    );
    ctx.stroke();
}

// 全局函数
window.closeHelpModal = closeHelpModal;
window.closeMovieReviewModal = closeMovieReviewModal;

// 电影数据
const movieData = [
    {
        id: 1,
        title: "哈利波特与魔法石",
        year: "2001年",
        description: "哈利·波特发现自己是一个魔法师，并进入霍格沃茨魔法学校学习。在这里，他结识了罗恩和赫敏，并发现了关于自己身世的秘密。",
        poster: "图纸/电影/哈利波特1.png",
        director: "克里斯·哥伦布",
        runtime: "152分钟",
        genre: "奇幻/冒险",
        rating: "PG",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "哈利·波特在11岁生日那天得知自己是一个魔法师，并收到了霍格沃茨魔法学校的录取通知书。在那里，他结识了最好的朋友罗恩·韦斯莱和赫敏·格兰杰，并发现了关于自己父母死亡的真相。",
        imdbRating: 7.6,
        rottenTomatoes: 81,
        metacritic: 64,
        boxOffice: "9.74亿美元",
        awards: "奥斯卡最佳艺术指导提名、最佳服装设计提名、最佳原创配乐提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rrjbdi0s.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    },
    {
        id: 2,
        title: "哈利波特与密室",
        year: "2002年",
        description: "霍格沃茨的学生们被石化，哈利发现了一个神秘的密室。他与罗恩和赫敏一起调查真相，最终面对了蛇怪和年轻的伏地魔。",
        poster: "图纸/电影/哈利波特2.png",
        director: "克里斯·哥伦布",
        runtime: "161分钟",
        genre: "奇幻/冒险",
        rating: "PG",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "霍格沃茨的学生们开始被石化，墙上出现了神秘的警告信息。哈利发现自己能听懂蛇的语言，这让他成为怀疑的对象。最终，他发现了密室的秘密，并面对了年轻的伏地魔。",
        imdbRating: 7.4,
        rottenTomatoes: 82,
        metacritic: 63,
        boxOffice: "8.79亿美元",
        awards: "奥斯卡最佳视觉效果提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rrjbeuig.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    },
    {
        id: 3,
        title: "哈利波特与阿兹卡班的囚徒",
        year: "2004年",
        description: "小天狼星·布莱克从阿兹卡班越狱，据说要杀死哈利。哈利发现了关于父母死亡的真相，并学会了守护神咒。",
        poster: "图纸/电影/哈利波特3.png",
        director: "阿方索·卡隆",
        runtime: "142分钟",
        genre: "奇幻/冒险",
        rating: "PG",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "小天狼星·布莱克从阿兹卡班越狱，据说要杀死哈利。哈利学会了守护神咒，并发现了关于父母死亡的真相。最终，他得知小天狼星实际上是他的教父。",
        imdbRating: 7.9,
        rottenTomatoes: 90,
        metacritic: 82,
        boxOffice: "7.97亿美元",
        awards: "奥斯卡最佳视觉效果提名、最佳原创配乐提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rrjbevto.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    },
    {
        id: 4,
        title: "哈利波特与火焰杯",
        year: "2005年",
        description: "霍格沃茨举办三强争霸赛，哈利意外被选中参赛。在比赛中，他发现了伏地魔的阴谋，并见证了黑魔王的复活。",
        poster: "图纸/电影/哈利波特4.png",
        director: "迈克·内威尔",
        runtime: "157分钟",
        genre: "奇幻/冒险",
        rating: "PG-13",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "霍格沃茨举办三强争霸赛，哈利意外被火焰杯选中参赛。在比赛中，他发现了伏地魔的阴谋，并见证了黑魔王的复活。塞德里克·迪戈里在比赛中牺牲。",
        imdbRating: 7.7,
        rottenTomatoes: 88,
        metacritic: 81,
        boxOffice: "8.96亿美元",
        awards: "奥斯卡最佳艺术指导提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rrjbfy7k.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    },
    {
        id: 5,
        title: "哈利波特与凤凰社",
        year: "2007年",
        description: "魔法部否认伏地魔的回归，哈利组建了邓布利多军。在神秘事务司的战斗中，小天狼星牺牲，哈利失去了教父。",
        poster: "图纸/电影/哈利波特5.png",
        director: "大卫·叶茨",
        runtime: "138分钟",
        genre: "奇幻/冒险",
        rating: "PG-13",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "魔法部否认伏地魔的回归，并派多洛雷斯·乌姆里奇到霍格沃茨。哈利组建了邓布利多军来学习防御魔法。在神秘事务司的战斗中，小天狼星牺牲。",
        imdbRating: 7.5,
        rottenTomatoes: 78,
        metacritic: 71,
        boxOffice: "9.42亿美元",
        awards: "奥斯卡最佳艺术指导提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rrjbevew.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    },
    {
        id: 6,
        title: "哈利波特与混血王子",
        year: "2009年",
        description: "邓布利多开始给哈利上课，讲述伏地魔的过去。斯内普杀死了邓布利多，霍格沃茨失去了最伟大的校长。",
        poster: "图纸/电影/哈利波特6.png",
        director: "大卫·叶茨",
        runtime: "153分钟",
        genre: "奇幻/冒险",
        rating: "PG",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "邓布利多开始给哈利上课，讲述伏地魔的过去和魂器的秘密。哈利发现了一个关于混血王子的魔药书。最终，斯内普杀死了邓布利多。",
        imdbRating: 7.6,
        rottenTomatoes: 84,
        metacritic: 78,
        boxOffice: "9.34亿美元",
        awards: "奥斯卡最佳摄影提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rrk47uq8.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    },
    {
        id: 7,
        title: "哈利波特与死亡圣器(上)",
        year: "2010年",
        description: "哈利、罗恩和赫敏离开霍格沃茨，寻找并摧毁魂器。他们面临重重危险，最终在戈德里克山谷失去了魔杖。",
        poster: "图纸/电影/哈利波特7上.png",
        director: "大卫·叶茨",
        runtime: "146分钟",
        genre: "奇幻/冒险",
        rating: "PG-13",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "哈利、罗恩和赫敏离开霍格沃茨，开始寻找并摧毁魂器的危险任务。他们面临重重危险，包括食死徒的追捕。最终在戈德里克山谷，哈利的魔杖被折断。",
        imdbRating: 7.7,
        rottenTomatoes: 78,
        metacritic: 65,
        boxOffice: "9.60亿美元",
        awards: "奥斯卡最佳艺术指导提名、最佳视觉效果提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rr9gh470.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    },
    {
        id: 8,
        title: "哈利波特与死亡圣器(下)",
        year: "2011年",
        description: "最后的战斗在霍格沃茨打响。哈利发现了自己也是魂器，最终击败了伏地魔，魔法世界重获和平。",
        poster: "图纸/电影/哈利波特7下.png",
        director: "大卫·叶茨",
        runtime: "130分钟",
        genre: "奇幻/冒险",
        rating: "PG-13",
        cast: "丹尼尔·雷德克里夫、艾玛·沃森、鲁伯特·格林特",
        plot: "最后的战斗在霍格沃茨打响。哈利发现了自己也是魂器，必须牺牲自己来击败伏地魔。最终，他击败了黑魔王，魔法世界重获和平。",
        imdbRating: 8.1,
        rottenTomatoes: 96,
        metacritic: 87,
        boxOffice: "13.42亿美元",
        awards: "奥斯卡最佳艺术指导提名、最佳视觉效果提名、最佳化妆提名",
        iqiyiUrl: "https://www.iqiyi.com/v_19rr9gh53c.html?s3=pca_115_IP_card&s4=0&vfrmblk=pca_115_IP_card&vfrm=3&s2=3&vfrmrst=0"
    }
];

// 电影回顾功能
function initMovieReview() {
    const movieReviewBtn = document.getElementById('movieReviewBtn');
    const movieReviewModal = document.getElementById('movieReviewModal');

    // 打开电影回顾模态框
    movieReviewBtn.addEventListener('click', function() {
        movieReviewModal.style.display = 'flex';
        movieReviewModal.style.opacity = '0';
        setTimeout(() => {
            movieReviewModal.style.opacity = '1';
        }, 10);
    });

    // 关闭电影回顾模态框
    window.closeMovieReviewModal = function() {
        movieReviewModal.style.opacity = '0';
        setTimeout(() => {
            movieReviewModal.style.display = 'none';
        }, 300);
    };

    // 点击模态框背景关闭
    movieReviewModal.addEventListener('click', function(e) {
        if (e.target === movieReviewModal) {
            closeMovieReviewModal();
        }
    });

    // 为每个电影海报添加双击事件（整个海报）
    const moviePosterItems = document.querySelectorAll('.movie-poster-item');
    moviePosterItems.forEach(item => {
        // 双击事件（整个海报）
        item.addEventListener('dblclick', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // 双击：跳转到爱奇艺
            const movieId = parseInt(this.getAttribute('data-movie'));
            openIqiyiMovie(movieId);
        });
    });
}

// 显示电影详情
function showMovieDetail(movieId) {
    const movie = movieData.find(m => m.id === movieId);
    if (!movie) {
        showNotification('未找到电影信息');
        return;
    }

    // 创建详情模态框
    const detailModal = document.createElement('div');
    detailModal.className = 'movie-detail-modal';
    detailModal.innerHTML = `
        <div class="movie-detail-content">
            <div class="movie-detail-header">
                <h2>🎬 ${movie.title}</h2>
                <button class="movie-detail-close" onclick="this.parentElement.parentElement.parentElement.remove()">×</button>
            </div>
            <div class="movie-detail-body">
                <div class="movie-detail-left">
                    <img src="${movie.poster}" alt="${movie.title}" class="movie-detail-poster">
                    <div class="movie-ratings">
                        <div class="rating-item">
                            <div class="rating-label">IMDb</div>
                            <div class="rating-score">${movie.imdbRating}/10</div>
                            <div class="rating-stars">
                                ${generateStars(movie.imdbRating / 2)}
                            </div>
                        </div>
                        <div class="rating-item">
                            <div class="rating-label">烂番茄</div>
                            <div class="rating-score">${movie.rottenTomatoes}%</div>
                            <div class="rating-bar">
                                <div class="rating-fill" style="width: ${movie.rottenTomatoes}%"></div>
                            </div>
                        </div>
                        <div class="rating-item">
                            <div class="rating-label">Metacritic</div>
                            <div class="rating-score">${movie.metacritic}/100</div>
                            <div class="rating-bar">
                                <div class="rating-fill" style="width: ${movie.metacritic}%"></div>
                            </div>
                        </div>
                    </div>
                    <div class="movie-watch-btn">
                        <button onclick="openIqiyiMovie(${movie.id})" class="watch-btn">
                            🎥 在爱奇艺观看
                        </button>
                    </div>
                </div>
                <div class="movie-detail-info">
                    <div class="movie-basic-info">
                        <h3>📋 基本信息</h3>
                        <p class="year">${movie.year}</p>
                        <p><strong>导演：</strong>${movie.director}</p>
                        <p><strong>时长：</strong>${movie.runtime}</p>
                        <p><strong>类型：</strong>${movie.genre}</p>
                        <p><strong>分级：</strong>${movie.rating}</p>
                        <p><strong>主演：</strong>${movie.cast}</p>
                        <p><strong>票房：</strong>${movie.boxOffice}</p>
                    </div>
                    <div class="movie-plot">
                        <h3>📖 剧情简介</h3>
                        <p>${movie.plot}</p>
                    </div>
                    <div class="movie-awards">
                        <h3>🏆 获奖情况</h3>
                        <p>${movie.awards}</p>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(detailModal);
    
    // 显示动画
    setTimeout(() => {
        detailModal.style.display = 'flex';
        detailModal.style.opacity = '0';
        setTimeout(() => {
            detailModal.style.opacity = '1';
        }, 10);
    }, 100);

    // 点击背景关闭
    detailModal.addEventListener('click', function(e) {
        if (e.target === detailModal) {
            detailModal.style.opacity = '0';
            setTimeout(() => {
                detailModal.remove();
            }, 300);
        }
    });
    
    // 显示成功通知
    showNotification(`已显示《${movie.title}》的详细信息`);
}

// 生成星级评分
function generateStars(rating) {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);
    
    let stars = '';
    for (let i = 0; i < fullStars; i++) {
        stars += '⭐';
    }
    if (hasHalfStar) {
        stars += '⭐';
    }
    for (let i = 0; i < emptyStars; i++) {
        stars += '☆';
    }
    return stars;
}

// 打开爱奇艺电影页面
function openIqiyiMovie(movieId) {
    const movie = movieData.find(m => m.id === movieId);
    if (!movie) {
        showNotification('未找到电影信息');
        return;
    }
    
    // 使用具体的电影播放链接
    const iqiyiUrl = movie.iqiyiUrl;
    
    // 显示确认对话框
    const confirmMessage = `即将跳转到爱奇艺观看《${movie.title}》，是否继续？\n\n您将被直接带到该电影的播放页面。`;
    if (confirm(confirmMessage)) {
        try {
            // 在新标签页中打开具体的电影播放页面
            const newWindow = window.open(iqiyiUrl, '_blank');
            
            if (newWindow) {
                showNotification(`已跳转到爱奇艺观看《${movie.title}》`);
                console.log(`成功跳转到爱奇艺: ${iqiyiUrl}`);
            } else {
                showNotification('跳转失败，请检查浏览器弹窗设置');
            }
        } catch (error) {
            console.error('跳转到爱奇艺失败:', error);
            showNotification('跳转失败，请重试');
        }
    }
}


